diff --git a/EATSSU/App/Resources/en.lproj/Localizable.strings b/EATSSU/App/Resources/en.lproj/Localizable.strings index 90a2bb9e..11344be1 100644 --- a/EATSSU/App/Resources/en.lproj/Localizable.strings +++ b/EATSSU/App/Resources/en.lproj/Localizable.strings @@ -499,6 +499,8 @@ "restaurant.snackCorner" = "Snack Corner"; /// "FACULTY (교직원 전용)" "restaurant.facultyRestaurant" = "FACULTY (Faculty Only)"; +/// "교직원 식당" (칩 등 좁은 곳) +"restaurant.facultyRestaurantShort" = "Faculty"; // MARK: - Review Translation @@ -741,3 +743,21 @@ "like.menuSearchEmptySubtitle" = "Try searching for a different menu name!"; /// "2글자 이상 입력해주세요." "like.menuSearchTooShort" = "Please enter at least 2 characters."; +/// "오늘 식단에서 찜하기" +"like.todayMenuToggle" = "Save from today's menu"; +/// "메뉴를 선택해 찜할 수 있어요." +"like.todayMenuHint" = "Select menus to save."; +/// "변경" +"like.change" = "Change"; +/// "메뉴 찜하기" +"like.favoriteMenus" = "Save menus"; +/// "선택한 %d개 메뉴 찜하기" +"like.favoriteSelectedMenus" = "Save %d selected"; +/// "메뉴 변경" +"like.slotSheetTitle" = "Change menu"; +/// "식당 종류" +"like.restaurantSection" = "Restaurant"; +/// "시간대" +"like.mealTimeSection" = "Meal time"; +/// "적용하기" +"like.apply" = "Apply"; diff --git a/EATSSU/App/Resources/ja.lproj/Localizable.strings b/EATSSU/App/Resources/ja.lproj/Localizable.strings index 48289079..7af57301 100644 --- a/EATSSU/App/Resources/ja.lproj/Localizable.strings +++ b/EATSSU/App/Resources/ja.lproj/Localizable.strings @@ -500,6 +500,8 @@ "restaurant.snackCorner" = "スナックコーナー"; /// "FACULTY (교직원 전용)" "restaurant.facultyRestaurant" = "FACULTY(教職員専用)"; +/// "교직원 식당" (칩 등 좁은 곳) +"restaurant.facultyRestaurantShort" = "教職員食堂"; // MARK: - Review Translation @@ -742,3 +744,21 @@ "like.menuSearchEmptySubtitle" = "別のメニュー名で検索してください!"; /// "2글자 이상 입력해주세요." "like.menuSearchTooShort" = "2文字以上入力してください。"; +/// "오늘 식단에서 찜하기" +"like.todayMenuToggle" = "今日の献立から追加"; +/// "메뉴를 선택해 찜할 수 있어요." +"like.todayMenuHint" = "メニューを選んでお気に入りに追加できます。"; +/// "변경" +"like.change" = "変更"; +/// "메뉴 찜하기" +"like.favoriteMenus" = "お気に入りに追加"; +/// "선택한 %d개 메뉴 찜하기" +"like.favoriteSelectedMenus" = "選択した%d件を追加"; +/// "메뉴 변경" +"like.slotSheetTitle" = "メニュー変更"; +/// "식당 종류" +"like.restaurantSection" = "食堂"; +/// "시간대" +"like.mealTimeSection" = "時間帯"; +/// "적용하기" +"like.apply" = "適用"; diff --git a/EATSSU/App/Resources/ko.lproj/Localizable.strings b/EATSSU/App/Resources/ko.lproj/Localizable.strings index 0b8b3e14..392aa09e 100644 --- a/EATSSU/App/Resources/ko.lproj/Localizable.strings +++ b/EATSSU/App/Resources/ko.lproj/Localizable.strings @@ -500,6 +500,8 @@ "restaurant.snackCorner" = "스낵 코너"; /// "FACULTY (교직원 전용)" "restaurant.facultyRestaurant" = "FACULTY (교직원 전용)"; +/// "교직원 식당" (칩 등 좁은 곳) +"restaurant.facultyRestaurantShort" = "교직원 식당"; // MARK: - Review Translation @@ -742,3 +744,21 @@ "like.menuSearchEmptySubtitle" = "다른 메뉴명으로 검색해주세요!"; /// "2글자 이상 입력해주세요." "like.menuSearchTooShort" = "2글자 이상 입력해주세요."; +/// "오늘 식단에서 찜하기" +"like.todayMenuToggle" = "오늘 식단에서 찜하기"; +/// "메뉴를 선택해 찜할 수 있어요." +"like.todayMenuHint" = "메뉴를 선택해 찜할 수 있어요."; +/// "변경" +"like.change" = "변경"; +/// "메뉴 찜하기" +"like.favoriteMenus" = "메뉴 찜하기"; +/// "선택한 %d개 메뉴 찜하기" +"like.favoriteSelectedMenus" = "선택한 %d개 메뉴 찜하기"; +/// "메뉴 변경" +"like.slotSheetTitle" = "메뉴 변경"; +/// "식당 종류" +"like.restaurantSection" = "식당 종류"; +/// "시간대" +"like.mealTimeSection" = "시간대"; +/// "적용하기" +"like.apply" = "적용하기"; diff --git a/EATSSU/App/Resources/vi.lproj/Localizable.strings b/EATSSU/App/Resources/vi.lproj/Localizable.strings index afffdbfa..97c48d71 100644 --- a/EATSSU/App/Resources/vi.lproj/Localizable.strings +++ b/EATSSU/App/Resources/vi.lproj/Localizable.strings @@ -500,6 +500,8 @@ "restaurant.snackCorner" = "Quầy đồ ăn nhẹ"; /// "FACULTY (교직원 전용)" "restaurant.facultyRestaurant" = "FACULTY (Chỉ dành cho giảng viên/nhân viên)"; +/// "교직원 식당" (칩 등 좁은 곳) +"restaurant.facultyRestaurantShort" = "Nhà ăn giảng viên"; // MARK: - Review Translation @@ -742,3 +744,21 @@ "like.menuSearchEmptySubtitle" = "Hãy thử tìm bằng tên món ăn khác!"; /// "2글자 이상 입력해주세요." "like.menuSearchTooShort" = "Vui lòng nhập ít nhất 2 ký tự."; +/// "오늘 식단에서 찜하기" +"like.todayMenuToggle" = "Lưu từ thực đơn hôm nay"; +/// "메뉴를 선택해 찜할 수 있어요." +"like.todayMenuHint" = "Chọn món để lưu."; +/// "변경" +"like.change" = "Đổi"; +/// "메뉴 찜하기" +"like.favoriteMenus" = "Lưu món"; +/// "선택한 %d개 메뉴 찜하기" +"like.favoriteSelectedMenus" = "Lưu %d món đã chọn"; +/// "메뉴 변경" +"like.slotSheetTitle" = "Đổi thực đơn"; +/// "식당 종류" +"like.restaurantSection" = "Nhà ăn"; +/// "시간대" +"like.mealTimeSection" = "Bữa ăn"; +/// "적용하기" +"like.apply" = "Áp dụng"; diff --git a/EATSSU/App/Sources/Notification/PushRoute.swift b/EATSSU/App/Sources/Notification/PushRoute.swift index a41d83ec..2168ad00 100644 --- a/EATSSU/App/Sources/Notification/PushRoute.swift +++ b/EATSSU/App/Sources/Notification/PushRoute.swift @@ -9,20 +9,8 @@ import UIKit /// 학식 알림을 눌렀을 때 이동할 학식 화면 (날짜 + 시간대) struct PushRoute { - /// 학식 탭 시간대 순서 (아침·점심·저녁) - enum MealTime: String { - case morning = "MORNING" - case lunch = "LUNCH" - case dinner = "DINNER" - - var tabIndex: Int { - switch self { - case .morning: 0 - case .lunch: 1 - case .dinner: 2 - } - } - } + /// 학식 탭 시간대 (아침·점심·저녁). 찜 탭 "오늘 식단에서 찜하기"와 같은 타입을 쓴다 + typealias MealTime = MealTimePart let date: Date /// 찜 알림에만 있다. 없으면(일반 학식 알림) 현재 시각 기준 시간대를 그대로 쓴다 @@ -35,22 +23,13 @@ struct PushRoute { guard let type = userInfo["type"] as? String, Self.supportedTypes.contains(type), let dateString = userInfo["date"] as? String, - let date = Self.dateFormatter.date(from: dateString) else { return nil } + let date = DateFormatter.serverDay.date(from: dateString) else { return nil } self.date = date self.mealTime = (userInfo["timePart"] as? String).flatMap(MealTime.init(rawValue:)) self.notificationId = (userInfo["notificationId"] as? String).flatMap(Int.init) } private static let supportedTypes: Set = ["MENU_FAVORITE", "DAILY_MENU"] - - private static let dateFormatter: DateFormatter = { - let formatter = DateFormatter() - formatter.calendar = Calendar(identifier: .gregorian) - formatter.locale = Locale(identifier: "en_US_POSIX") - formatter.timeZone = .current - formatter.dateFormat = "yyyyMMdd" - return formatter - }() } /// 알림을 누른 시점에 화면이 준비돼 있지 않을 수 있어(앱 실행 직후 스플래시·로그인 등) 이동할 곳을 보관했다가 적용한다 diff --git a/EATSSU/App/Sources/Presentation/Home/Enum/MealTimePart.swift b/EATSSU/App/Sources/Presentation/Home/Enum/MealTimePart.swift new file mode 100644 index 00000000..caaf0e3b --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Home/Enum/MealTimePart.swift @@ -0,0 +1,33 @@ +// +// MealTimePart.swift +// EATSSU +// +// Created by 황상환 on 11/8/26. +// + +import Foundation + +/// 학식 시간대. rawValue는 서버 `timePart` 값이며 학식 탭 순서(아침·점심·저녁)와 같다 +enum MealTimePart: String, CaseIterable { + case morning = "MORNING" + case lunch = "LUNCH" + case dinner = "DINNER" + + /// 학식 탭의 시간대 탭 인덱스 + var tabIndex: Int { + switch self { + case .morning: 0 + case .lunch: 1 + case .dinner: 2 + } + } + + /// 현재 앱 언어의 시간대 이름 + var title: String { + switch self { + case .morning: TextLiteral.Home.morning + case .lunch: TextLiteral.Home.lunch + case .dinner: TextLiteral.Home.dinner + } + } +} diff --git a/EATSSU/App/Sources/Presentation/Home/Enum/RestaurantType.swift b/EATSSU/App/Sources/Presentation/Home/Enum/RestaurantType.swift index 165bc34e..7fb47013 100644 --- a/EATSSU/App/Sources/Presentation/Home/Enum/RestaurantType.swift +++ b/EATSSU/App/Sources/Presentation/Home/Enum/RestaurantType.swift @@ -60,6 +60,14 @@ enum Restaurant: String, CaseIterable { } } + /// 칩처럼 좁은 곳에 쓰는 이름. 교직원 식당만 "FACULTY (교직원 전용)" 대신 짧은 이름을 쓴다 + var shortTitle: String { + switch self { + case .facultyRestaurant: TextLiteral.Restaurant.facultyRestaurantShort + default: title + } + } + /// Firebase Remote Config `cafeteria_information`의 `name`과 매칭하기 위한 한국어 이름 // TODO: Remote Config에 id가 추가되면 이름 대신 id로 매칭하도록 변경 var koreanName: String { diff --git a/EATSSU/App/Sources/Presentation/Home/ViewController/HomeRestaurantViewController.swift b/EATSSU/App/Sources/Presentation/Home/ViewController/HomeRestaurantViewController.swift index 05a92076..57d632f8 100644 --- a/EATSSU/App/Sources/Presentation/Home/ViewController/HomeRestaurantViewController.swift +++ b/EATSSU/App/Sources/Presentation/Home/ViewController/HomeRestaurantViewController.swift @@ -218,16 +218,9 @@ final class HomeRestaurantViewController: BaseViewController { // 날짜를 yyyyMMdd 문자열로 변환 private func changeDateFormat(date: Date) -> String { - return Self.yyyyMMddDateFormatter.string(from: date) + return DateFormatter.serverDay.string(from: date) } - ///"yyyyMMdd 포맷팅하기 위한 DateFormatter 인스턴스 - private static let yyyyMMddDateFormatter: DateFormatter = { - let formatter = DateFormatter() - formatter.dateFormat = "yyyyMMdd" - return formatter - }() - /// 스낵코너 메뉴를 비우고 UI를 갱신 private func hideSnackCorner() { isSelectable = false diff --git a/EATSSU/App/Sources/Presentation/Like/Model/TodayMenuSlot.swift b/EATSSU/App/Sources/Presentation/Like/Model/TodayMenuSlot.swift new file mode 100644 index 00000000..916db821 --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Like/Model/TodayMenuSlot.swift @@ -0,0 +1,41 @@ +// +// TodayMenuSlot.swift +// EATSSU +// +// Created by 황상환 on 11/8/26. +// + +import Foundation + +/// "오늘 식단에서 찜하기"에서 고른 식당·시간대 +struct TodayMenuSlot: Equatable { + let restaurant: Restaurant + let mealTime: MealTimePart + + /// 찜 탭으로 들어왔을 때의 기본값 (기능 명세: 학생식당 · 점심) + static let `default` = TodayMenuSlot(restaurant: .studentRestaurant, mealTime: .lunch) + + /// 바텀시트에서 고를 수 있는 식당. 스낵코너는 메뉴가 고정이라 찜 대상이 아니다 (디자인 기준 4곳) + static let selectableRestaurants: [Restaurant] = [ + .studentRestaurant, .dodamRestaurant, .dormitoryRestaurant, .facultyRestaurant + ] + + /// 식당마다 운영하지 않는 시간대가 있다 (기능 명세) + /// 학생식당 저녁 미운영 · 도담식당 아침 미운영 · 기숙사식당 아침 미운영 · 교직원식당 아침·저녁 미운영 + static func isAvailable(restaurant: Restaurant, mealTime: MealTimePart) -> Bool { + switch restaurant { + case .studentRestaurant: mealTime != .dinner + case .dodamRestaurant, .dormitoryRestaurant: mealTime != .morning + case .facultyRestaurant, .snackCorner: mealTime == .lunch + } + } + + var isAvailable: Bool { + Self.isAvailable(restaurant: restaurant, mealTime: mealTime) + } + + /// "학생 식당 · 점심" + var title: String { + "\(restaurant.shortTitle) · \(mealTime.title)" + } +} diff --git a/EATSSU/App/Sources/Presentation/Like/View/MenuChipFlowView.swift b/EATSSU/App/Sources/Presentation/Like/View/MenuChipFlowView.swift new file mode 100644 index 00000000..ef824194 --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Like/View/MenuChipFlowView.swift @@ -0,0 +1,130 @@ +// +// MenuChipFlowView.swift +// EATSSU +// +// Created by 황상환 on 11/8/26. +// + +import UIKit + +import EATSSUDesign + +/// 메뉴명 칩을 가로로 늘어놓다가 폭이 모자라면 다음 줄로 넘기는 뷰 (다국어 메뉴명 길이 대응) +/// +/// 디자인: 칩 높이 27, 모서리 13.5, 좌우 안쪽 9, Medium 10, 가로 간격 7, 세로 간격 9 +/// 기본: 흰 배경 · gray300 테두리 · gray600 글자 / 선택: secondary 배경 · primary 테두리 · gray700 글자 +final class MenuChipFlowView: UIView { + + // MARK: - Types + + struct Item: Equatable { + let id: Int + let title: String + /// 이미 찜한 메뉴. 선택된 모양으로 보이고 누를 수 없다 (해제는 "내가 찜한 메뉴" 목록에서만) + let isLocked: Bool + } + + // MARK: - Constants + + private enum Layout { + static let chipHeight: CGFloat = 27 + static let horizontalPadding: CGFloat = 9 + static let horizontalSpacing: CGFloat = 7 + static let verticalSpacing: CGFloat = 9 + } + + // MARK: - Properties + + var onSelectionChanged: ((Set) -> Void)? + + private(set) var items: [Item] = [] + private(set) var selectedIds: Set = [] + private var chips: [UIButton] = [] + private var lastLayoutWidth: CGFloat = 0 + private var contentHeight: CGFloat = 0 + + // MARK: - Configuration + + func configure(items: [Item], selectedIds: Set) { + self.items = items + self.selectedIds = selectedIds.intersection(Set(items.filter { !$0.isLocked }.map(\.id))) + chips.forEach { $0.removeFromSuperview() } + chips = items.enumerated().map { index, item in + let chip = UIButton(type: .custom) + chip.setTitle(item.title, for: .normal) + chip.titleLabel?.font = .caption3 + chip.titleLabel?.lineBreakMode = .byTruncatingTail + chip.contentEdgeInsets = UIEdgeInsets(top: 0, left: Layout.horizontalPadding, bottom: 0, right: Layout.horizontalPadding) + chip.layer.cornerRadius = Layout.chipHeight / 2 + chip.layer.borderWidth = 1 + chip.tag = index + chip.isEnabled = !item.isLocked + chip.addTarget(self, action: #selector(didTapChip(_:)), for: .touchUpInside) + addSubview(chip) + return chip + } + applySelection() + lastLayoutWidth = 0 + setNeedsLayout() + invalidateIntrinsicContentSize() + } + + func clearSelection() { + selectedIds = [] + applySelection() + } + + // MARK: - Layout + + override var intrinsicContentSize: CGSize { + CGSize(width: UIView.noIntrinsicMetric, height: contentHeight) + } + + override func layoutSubviews() { + super.layoutSubviews() + let width = bounds.width + guard width > 0 else { return } + var x: CGFloat = 0 + var y: CGFloat = 0 + for chip in chips { + let fitting = chip.sizeThatFits(CGSize(width: width, height: Layout.chipHeight)) + let chipWidth = min(ceil(fitting.width), width) + if x > 0, x + chipWidth > width { + x = 0 + y += Layout.chipHeight + Layout.verticalSpacing + } + chip.frame = CGRect(x: x, y: y, width: chipWidth, height: Layout.chipHeight) + x += chipWidth + Layout.horizontalSpacing + } + let newHeight = chips.isEmpty ? 0 : y + Layout.chipHeight + if newHeight != contentHeight || width != lastLayoutWidth { + contentHeight = newHeight + lastLayoutWidth = width + invalidateIntrinsicContentSize() + } + } + + // MARK: - Private + + @objc private func didTapChip(_ sender: UIButton) { + guard items.indices.contains(sender.tag) else { return } + let id = items[sender.tag].id + if selectedIds.contains(id) { + selectedIds.remove(id) + } else { + selectedIds.insert(id) + } + applySelection() + onSelectionChanged?(selectedIds) + } + + private func applySelection() { + for (chip, item) in zip(chips, items) { + let isHighlighted = item.isLocked || selectedIds.contains(item.id) + chip.backgroundColor = isHighlighted ? .secondary : .white + chip.layer.borderColor = (isHighlighted ? UIColor.primary : UIColor.gray300).cgColor + chip.setTitleColor(isHighlighted ? .gray700 : .gray600, for: .normal) + chip.setTitleColor(.gray700, for: .disabled) + } + } +} diff --git a/EATSSU/App/Sources/Presentation/Like/View/TodayMenuFavoriteCardView.swift b/EATSSU/App/Sources/Presentation/Like/View/TodayMenuFavoriteCardView.swift new file mode 100644 index 00000000..a379fdc8 --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Like/View/TodayMenuFavoriteCardView.swift @@ -0,0 +1,270 @@ +// +// TodayMenuFavoriteCardView.swift +// EATSSU +// +// Created by 황상환 on 11/8/26. +// + +import UIKit + +import SnapKit + +import EATSSUDesign + +/// "오늘 식단에서 찜하기" 카드. 접힌 상태는 제목 한 줄, 펼치면 식당·시간대 · 변경 버튼 · 메뉴 칩 · 찜하기 버튼 +/// +/// 디자인(390 기준): 카드 좌우 24, 모서리 8, gray300 테두리. 헤더 41(아이콘 20 좌 9, 제목 Medium 12, 화살표 우 9) +/// 펼침: 식당·시간대 Bold 16(좌 11, 헤더 아래 10) · 변경 36×25(우 11) · 안내 Medium 12 gray400(아래 6) +/// 칩 영역(안내 아래 16, 좌우 9) · 버튼 40(칩 아래 12, 좌우 9, 모서리 8) · 아래 여백 10 +final class TodayMenuFavoriteCardView: UIView { + + // MARK: - Constants + + private enum Layout { + static let cornerRadius: CGFloat = 8 + static let headerHeight: CGFloat = 41 + static let iconLeading: CGFloat = 9 + static let iconSize: CGFloat = 20 + static let titleLeading: CGFloat = 33 + static let chevronTrailing: CGFloat = 9 + static let textInset: CGFloat = 11 + static let contentInset: CGFloat = 9 + static let slotTop: CGFloat = 10 + static let hintTop: CGFloat = 6 + static let chipsTop: CGFloat = 16 + static let buttonTop: CGFloat = 12 + static let buttonHeight: CGFloat = 40 + static let buttonCornerRadius: CGFloat = 8 + static let bottomInset: CGFloat = 10 + static let changeButtonSize = CGSize(width: 36, height: 25) + static let disabledAlpha: CGFloat = 0.5 + } + + // MARK: - Properties + + var onToggle: (() -> Void)? + var onTapChange: (() -> Void)? + var onTapSubmit: (() -> Void)? + /// 선택이 바뀌어 버튼 문구가 바뀔 때. 높이는 변하지 않는다 + var onSelectionChanged: ((Set) -> Void)? + + private(set) var isExpanded = false + + var selectedIds: Set { chipFlowView.selectedIds } + + /// 접힘: 헤더 바닥 = 카드 바닥 / 펼침: 내용 바닥 = 카드 바닥. 둘 중 하나만 켠다 + private var collapsedBottomConstraint: Constraint? + private var expandedBottomConstraint: Constraint? + + // MARK: - UI Components + + private let headerButton = UIButton(type: .custom) + private let iconImageView = UIImageView(image: EATSSUDesignAsset.Images.icCalendar.image) + private let titleLabel = UILabel() + private let chevronImageView = UIImageView() + + private let contentView = UIView() + private let slotLabel = UILabel() + private let changeButton = UIButton(type: .system) + private let hintLabel = UILabel() + /// 칩 또는 "메뉴 없음" 문구가 들어가는 영역. 둘 중 큰 쪽 높이를 가진다 + private let chipAreaView = UIView() + private let chipFlowView = MenuChipFlowView() + private let noMenuLabel = UILabel() + private let submitButton = UIButton(type: .custom) + + // MARK: - Init + + override init(frame: CGRect) { + super.init(frame: frame) + configureUI() + setLayout() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - View Setup + + private func configureUI() { + backgroundColor = .white + layer.cornerRadius = Layout.cornerRadius + layer.borderWidth = 1 + layer.borderColor = UIColor.gray300.cgColor + clipsToBounds = true + + iconImageView.tintColor = .gray400 + iconImageView.contentMode = .scaleAspectFit + + titleLabel.text = TextLiteral.Like.todayMenuToggle + titleLabel.font = .caption2 + titleLabel.textColor = .gray700 + + let chevronConfig = UIImage.SymbolConfiguration(pointSize: 12, weight: .medium) + chevronImageView.image = UIImage(systemName: "chevron.down", withConfiguration: chevronConfig) + chevronImageView.tintColor = .gray400 + chevronImageView.contentMode = .center + + slotLabel.font = .subtitle1 + slotLabel.textColor = .gray700 + + changeButton.setTitle(TextLiteral.Like.change, for: .normal) + changeButton.titleLabel?.font = .caption2 + changeButton.setTitleColor(.gray600, for: .normal) + changeButton.layer.cornerRadius = 4 + changeButton.layer.borderWidth = 1 + changeButton.layer.borderColor = UIColor.gray300.cgColor + + hintLabel.text = TextLiteral.Like.todayMenuHint + hintLabel.font = .caption2 + hintLabel.textColor = .gray400 + + noMenuLabel.text = TextLiteral.Home.noMenuProvidedMessage + noMenuLabel.font = .caption2 + noMenuLabel.textColor = .gray500 + noMenuLabel.isHidden = true + + submitButton.titleLabel?.font = .button2 + submitButton.setTitleColor(.white, for: .normal) + submitButton.backgroundColor = .primary + submitButton.layer.cornerRadius = Layout.buttonCornerRadius + + contentView.isHidden = true + + headerButton.accessibilityIdentifier = "like.todayMenuCard.header" + headerButton.accessibilityLabel = TextLiteral.Like.todayMenuToggle + changeButton.accessibilityIdentifier = "like.todayMenuCard.change" + submitButton.accessibilityIdentifier = "like.todayMenuCard.submit" + headerButton.addTarget(self, action: #selector(didTapHeader), for: .touchUpInside) + changeButton.addTarget(self, action: #selector(didTapChange), for: .touchUpInside) + submitButton.addTarget(self, action: #selector(didTapSubmit), for: .touchUpInside) + chipFlowView.onSelectionChanged = { [weak self] ids in + self?.updateSubmitButton() + self?.onSelectionChanged?(ids) + } + + chipAreaView.addSubviews(chipFlowView, noMenuLabel) + contentView.addSubviews(slotLabel, changeButton, hintLabel, chipAreaView, submitButton) + addSubviews(headerButton, iconImageView, titleLabel, chevronImageView, contentView) + updateSubmitButton() + } + + private func setLayout() { + headerButton.snp.makeConstraints { + $0.top.leading.trailing.equalToSuperview() + $0.height.equalTo(Layout.headerHeight) + collapsedBottomConstraint = $0.bottom.equalToSuperview().constraint + } + iconImageView.snp.makeConstraints { + $0.leading.equalToSuperview().inset(Layout.iconLeading) + $0.centerY.equalTo(headerButton) + $0.size.equalTo(Layout.iconSize) + } + titleLabel.snp.makeConstraints { + $0.leading.equalToSuperview().inset(Layout.titleLeading) + $0.centerY.equalTo(headerButton) + $0.trailing.lessThanOrEqualTo(chevronImageView.snp.leading).offset(-8) + } + chevronImageView.snp.makeConstraints { + $0.trailing.equalToSuperview().inset(Layout.chevronTrailing) + $0.centerY.equalTo(headerButton) + $0.size.equalTo(18) + } + + contentView.snp.makeConstraints { + $0.top.equalTo(headerButton.snp.bottom) + $0.leading.trailing.equalToSuperview() + expandedBottomConstraint = $0.bottom.equalToSuperview().constraint + } + expandedBottomConstraint?.deactivate() + + slotLabel.snp.makeConstraints { + $0.top.equalToSuperview().offset(Layout.slotTop) + $0.leading.equalToSuperview().inset(Layout.textInset) + $0.trailing.lessThanOrEqualTo(changeButton.snp.leading).offset(-8) + } + changeButton.snp.makeConstraints { + $0.centerY.equalTo(slotLabel) + $0.trailing.equalToSuperview().inset(Layout.textInset) + $0.size.equalTo(Layout.changeButtonSize) + } + hintLabel.snp.makeConstraints { + $0.top.equalTo(slotLabel.snp.bottom).offset(Layout.hintTop) + $0.leading.trailing.equalToSuperview().inset(Layout.textInset) + } + chipAreaView.snp.makeConstraints { + $0.top.equalTo(hintLabel.snp.bottom).offset(Layout.chipsTop) + $0.leading.trailing.equalToSuperview().inset(Layout.contentInset) + // 칩과 안내 문구 중 보이는 쪽의 높이만큼만 차지한다 + $0.height.equalTo(0).priority(.low) + } + chipFlowView.snp.makeConstraints { + $0.top.leading.trailing.equalToSuperview() + $0.bottom.lessThanOrEqualToSuperview() + } + noMenuLabel.snp.makeConstraints { + $0.top.equalToSuperview() + $0.leading.trailing.equalToSuperview().inset(Layout.textInset - Layout.contentInset) + $0.bottom.lessThanOrEqualToSuperview() + } + submitButton.snp.makeConstraints { + $0.top.equalTo(chipAreaView.snp.bottom).offset(Layout.buttonTop) + $0.leading.trailing.equalToSuperview().inset(Layout.contentInset) + $0.height.equalTo(Layout.buttonHeight) + $0.bottom.equalToSuperview().inset(Layout.bottomInset) + } + } + + // MARK: - Configuration + + func setExpanded(_ expanded: Bool) { + isExpanded = expanded + contentView.isHidden = !expanded + chevronImageView.transform = expanded ? CGAffineTransform(rotationAngle: .pi) : .identity + if expanded { + collapsedBottomConstraint?.deactivate() + expandedBottomConstraint?.activate() + } else { + expandedBottomConstraint?.deactivate() + collapsedBottomConstraint?.activate() + } + } + + /// - Parameter showsNoMenu: 메뉴를 받아왔는데 비어 있을 때만 true. 불러오는 중이거나 실패했을 때는 칩 자리를 비워 둔다 + func configure(slot: TodayMenuSlot, items: [MenuChipFlowView.Item], selectedIds: Set, showsNoMenu: Bool) { + slotLabel.text = slot.title + chipFlowView.configure(items: items, selectedIds: selectedIds) + noMenuLabel.isHidden = !(items.isEmpty && showsNoMenu) + chipFlowView.isHidden = items.isEmpty + updateSubmitButton() + } + + func clearSelection() { + chipFlowView.clearSelection() + updateSubmitButton() + } + + // MARK: - Private + + private func updateSubmitButton() { + let count = chipFlowView.selectedIds.count + let title = count == 0 ? TextLiteral.Like.favoriteMenus : TextLiteral.Like.favoriteSelectedMenus(count) + submitButton.setTitle(title, for: .normal) + submitButton.isEnabled = count > 0 + submitButton.alpha = count > 0 ? 1 : Layout.disabledAlpha + } + + @objc private func didTapHeader() { + onToggle?() + } + + @objc private func didTapChange() { + onTapChange?() + } + + @objc private func didTapSubmit() { + onTapSubmit?() + } +} diff --git a/EATSSU/App/Sources/Presentation/Like/ViewController/MenuLikeViewController.swift b/EATSSU/App/Sources/Presentation/Like/ViewController/MenuLikeViewController.swift index 40b9f2b5..5deb2f8f 100644 --- a/EATSSU/App/Sources/Presentation/Like/ViewController/MenuLikeViewController.swift +++ b/EATSSU/App/Sources/Presentation/Like/ViewController/MenuLikeViewController.swift @@ -12,28 +12,39 @@ import SnapKit import EATSSUDesign -/// 메뉴 찜: 검색창 + (검색어 2글자 미만) 내가 찜한 메뉴 / (2글자 이상) 검색 결과 +/// 메뉴 찜: 검색창 + "오늘 식단에서 찜하기" 카드 + 내가 찜한 메뉴 +/// +/// - 검색창에 포커스가 가면 카드와 찜 목록을 숨기고, 2글자 이상이면 검색 결과를 보여준다 (기능 명세) +/// - X나 포커스 해제로 검색을 끝내면 카드가 접힌 찜 목록으로 돌아온다 final class MenuLikeViewController: BaseViewController { // MARK: - Types private enum Mode { case favorites + /// 검색창에 포커스만 있고 검색어가 2글자 미만. 키보드와 흰 화면만 보인다 + case searchIdle /// 검색 결과 표시 중. `didFail`이면 결과 없음 안내 대신 빈 화면 + 실패 토스트 case search(keyword: String, menus: [MenuSearchDTO], didFail: Bool) + + var isFavorites: Bool { + if case .favorites = self { return true } + return false + } } // MARK: - Constants - /// 디자인(탭 밑줄 아래 기준): 검색창 top 24 · 좌우 24 - /// 찜 목록: 제목 중심 검색창 아래 34, 구분선 검색창 아래 57(좌우 26), 첫 행 검색창 아래 64 + /// 디자인(탭 밑줄 아래 기준): 검색창 top 24 · 좌우 24 · 카드는 검색창 아래 21 + /// 찜 목록: 제목 중심 카드 아래 28.5, 구분선 제목 중심 아래 23(좌우 26), 첫 행 제목 중심 아래 30 /// 검색 결과: 첫 행 검색창 아래 15 private enum Layout { static let searchBarTop: CGFloat = 24 static let horizontalInset: CGFloat = 24 - static let favoritesHeaderHeight: CGFloat = 64 - static let favoritesTitleCenterY: CGFloat = 34 - static let favoritesSeparatorTop: CGFloat = 57 + static let cardTop: CGFloat = 21 + static let favoritesTitleCenterBelowCard: CGFloat = 28.5 + static let favoritesSeparatorBelowTitle: CGFloat = 23 + static let favoritesRowsBelowTitle: CGFloat = 30 static let favoritesInset: CGFloat = 26 static let searchResultsTop: CGFloat = 15 } @@ -51,15 +62,27 @@ final class MenuLikeViewController: BaseViewController { (searchBar.textField.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines) } + /// 오늘 식단에서 찜하기: 현재 식당·시간대와 그 메뉴 + private var todaySlot: TodayMenuSlot = .default + private var todayMenus: [BriefMenus] = [] + /// 오늘 메뉴를 성공적으로 받아왔는지. 불러오는 중·실패 상태에서는 "메뉴 없음" 문구를 보여주지 않는다 + private var hasLoadedTodayMenus = false + private var todayMenuGeneration = 0 + private var isSubmittingTodayMenus = false + // MARK: - UI Components private let searchBar = MenuSearchBar() private let tableView = UITableView(frame: .zero, style: .plain) private let emptyView = EmptyStateView() + private let todayMenuCard = TodayMenuFavoriteCardView() private lazy var favoritesHeaderView = makeFavoritesHeaderView() + private let favoritesTitleLabel = UILabel() + private let favoritesSeparator = UIView() private let searchResultsHeaderView = UIView( frame: CGRect(x: 0, y: 0, width: 0, height: Layout.searchResultsTop) ) + private var emptyViewTopConstraint: Constraint? // MARK: - View Setup @@ -85,7 +108,7 @@ final class MenuLikeViewController: BaseViewController { tapGesture.cancelsTouchesInView = false view.addGestureRecognizer(tapGesture) - view.addSubviews(emptyView, tableView, searchBar) + view.addSubviews(tableView, emptyView, searchBar) } override func setLayout() { @@ -99,9 +122,10 @@ final class MenuLikeViewController: BaseViewController { $0.leading.trailing.bottom.equalToSuperview() } - // 디자인의 안내 문구 위치는 탭 밑줄 아래 전체 영역 기준 약 45% 지점 + // 찜한 메뉴가 없을 때 안내 문구는 카드 아래 영역의 가운데 위쪽에 둔다 emptyView.snp.makeConstraints { - $0.edges.equalToSuperview() + emptyViewTopConstraint = $0.top.equalTo(tableView).constraint + $0.leading.trailing.bottom.equalToSuperview() } } @@ -116,6 +140,17 @@ final class MenuLikeViewController: BaseViewController { self.search(keyword: keyword) } .store(in: &cancellables) + + todayMenuCard.onToggle = { [weak self] in + guard let self else { return } + self.setTodayMenuExpanded(!self.todayMenuCard.isExpanded) + } + todayMenuCard.onTapChange = { [weak self] in + self?.presentSlotSheet() + } + todayMenuCard.onTapSubmit = { [weak self] in + self?.submitTodayMenus() + } } // MARK: - Life Cycle @@ -125,9 +160,14 @@ final class MenuLikeViewController: BaseViewController { reload() } + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + updateFavoritesHeaderHeight() + } + // MARK: - Public - /// 찜 목록을 다시 받고, 검색 중이면 같은 검색어로 다시 검색한다 + /// 찜 목록을 다시 받고, 검색 중이면 같은 검색어로 다시 검색한다. 카드가 펼쳐져 있으면 오늘 메뉴도 다시 받는다 func reload() { render() MenuFavoriteManager.shared.refresh { [weak self] result in @@ -145,6 +185,9 @@ final class MenuLikeViewController: BaseViewController { if case .search(let keyword, _, _) = mode, keyword == currentKeyword { search(keyword: keyword) } + if todayMenuCard.isExpanded { + loadTodayMenus() + } } // MARK: - Search @@ -152,9 +195,9 @@ final class MenuLikeViewController: BaseViewController { @objc private func textDidChange() { let keyword = currentKeyword guard keyword.count >= MenuFavoriteManager.minimumKeywordLength else { - // 2글자 미만: 진행 중인 검색 응답을 무시하고 바로 찜 목록으로 돌아간다 + // 2글자 미만: 진행 중인 검색 응답을 무시하고, 포커스 중이면 빈 화면·아니면 찜 목록으로 돌아간다 searchGeneration += 1 - mode = .favorites + mode = searchBar.textField.isFirstResponder ? .searchIdle : .favorites render() return } @@ -178,6 +221,14 @@ final class MenuLikeViewController: BaseViewController { } } + /// 검색을 끝내고(X 또는 포커스 해제) 카드가 접힌 찜 목록으로 돌아간다 + private func finishSearch() { + searchGeneration += 1 + searchBar.textField.text = nil + mode = .favorites + setTodayMenuExpanded(false) + } + // MARK: - Render private func render() { @@ -185,9 +236,17 @@ final class MenuLikeViewController: BaseViewController { case .favorites: let favorites = MenuFavoriteManager.shared.favorites let showsEmpty = MenuFavoriteManager.shared.hasLoaded && favorites.isEmpty - setTableHeader(favorites.isEmpty ? nil : favoritesHeaderView) + // 찜이 없어도 카드는 보인다. 제목·구분선은 찜이 있을 때만 + favoritesTitleLabel.isHidden = favorites.isEmpty + favoritesSeparator.isHidden = favorites.isEmpty + setTableHeader(favoritesHeaderView) emptyView.configure(title: TextLiteral.Like.menuEmptyTitle, subtitle: TextLiteral.Like.menuEmptySubtitle) emptyView.isHidden = !showsEmpty + tableView.isHidden = false + case .searchIdle: + setTableHeader(searchResultsHeaderView) + emptyView.isHidden = true + tableView.isHidden = true case .search(_, let menus, let didFail): setTableHeader(searchResultsHeaderView) emptyView.configure( @@ -195,10 +254,12 @@ final class MenuLikeViewController: BaseViewController { subtitle: TextLiteral.Like.menuSearchEmptySubtitle ) emptyView.isHidden = !(menus.isEmpty && !didFail) + // 안내 문구는 흰 배경 테이블 뒤에 있으므로, 보일 때는 테이블을 숨긴다 (제휴 찜 목록과 같은 방식) + tableView.isHidden = !emptyView.isHidden } - // 안내 문구는 흰 배경 테이블 뒤에 있으므로, 보일 때는 테이블을 숨긴다 (제휴 찜 목록과 같은 방식) - tableView.isHidden = !emptyView.isHidden + emptyViewTopConstraint?.update(offset: mode.isFavorites ? favoritesHeaderView.bounds.height : 0) tableView.reloadData() + updateFavoritesHeaderHeight() } private func setTableHeader(_ header: UIView?) { @@ -206,30 +267,160 @@ final class MenuLikeViewController: BaseViewController { tableView.tableHeaderView = header } + /// 카드가 접히거나 펼쳐지고 칩 줄 수가 바뀌면 헤더 높이가 달라지므로 다시 계산해 테이블에 반영한다 + private func updateFavoritesHeaderHeight() { + guard tableView.tableHeaderView === favoritesHeaderView, tableView.bounds.width > 0 else { return } + let width = tableView.bounds.width + // 칩 줄 수는 폭에 따라 달라지고 칩 높이는 레이아웃 때 계산되므로, 폭을 맞춰 한 번 레이아웃한 뒤 높이를 잰다 + favoritesHeaderView.frame.size.width = width + favoritesHeaderView.layoutIfNeeded() + let target = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height) + let height = favoritesHeaderView.systemLayoutSizeFitting( + target, + withHorizontalFittingPriority: .required, + verticalFittingPriority: .fittingSizeLevel + ).height + guard abs(favoritesHeaderView.bounds.height - height) > 0.5 else { return } + favoritesHeaderView.frame = CGRect(x: 0, y: 0, width: width, height: height) + tableView.tableHeaderView = favoritesHeaderView + emptyViewTopConstraint?.update(offset: height) + } + private func makeFavoritesHeaderView() -> UIView { - let header = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Layout.favoritesHeaderHeight)) + let header = UIView() - let titleLabel = UILabel() - titleLabel.text = TextLiteral.Like.menuListTitle - titleLabel.font = .subtitle2 - titleLabel.textColor = .gray700 + favoritesTitleLabel.text = TextLiteral.Like.menuListTitle + favoritesTitleLabel.font = .subtitle2 + favoritesTitleLabel.textColor = .gray700 - let separator = UIView() - separator.backgroundColor = .gray200 + favoritesSeparator.backgroundColor = .gray200 - header.addSubviews(titleLabel, separator) - titleLabel.snp.makeConstraints { + header.addSubviews(todayMenuCard, favoritesTitleLabel, favoritesSeparator) + todayMenuCard.snp.makeConstraints { + $0.top.equalToSuperview().offset(Layout.cardTop) + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + } + favoritesTitleLabel.snp.makeConstraints { $0.leading.equalToSuperview().inset(Layout.favoritesInset) - $0.centerY.equalTo(header.snp.top).offset(Layout.favoritesTitleCenterY) + $0.centerY.equalTo(todayMenuCard.snp.bottom).offset(Layout.favoritesTitleCenterBelowCard) } - separator.snp.makeConstraints { - $0.top.equalToSuperview().offset(Layout.favoritesSeparatorTop) + favoritesSeparator.snp.makeConstraints { + $0.top.equalTo(favoritesTitleLabel.snp.centerY).offset(Layout.favoritesSeparatorBelowTitle) $0.leading.trailing.equalToSuperview().inset(Layout.favoritesInset) $0.height.equalTo(1) + $0.bottom.equalToSuperview().inset(Layout.favoritesRowsBelowTitle - Layout.favoritesSeparatorBelowTitle - 1) } + todayMenuCard.setExpanded(false) return header } + // MARK: - Today Menu + + private func setTodayMenuExpanded(_ expanded: Bool) { + todayMenuCard.setExpanded(expanded) + if expanded { + renderTodayMenuCard() + loadTodayMenus() + } + render() + } + + private func loadTodayMenus() { + todayMenuGeneration += 1 + let generation = todayMenuGeneration + let slot = todaySlot + hasLoadedTodayMenus = false + NetworkService.shared.request( + HomeRouter.getChangeMenuTableResponse( + date: DateFormatter.serverDay.string(from: Date()), + restaurant: slot.restaurant.identifier, + time: slot.mealTime.rawValue, + language: ChangeMenuTableResponse.mealLanguageParameter + ), + responseType: [ChangeMenuTableResponse].self + ) { [weak self] result in + guard let self, generation == self.todayMenuGeneration, slot == self.todaySlot else { return } + switch result { + case .success(let meals): + // 학식 탭과 같은 메뉴를 보여준다(영어면 번역된 대표메뉴만). 한 시간대에 식단이 여러 개여도 메뉴는 한 번씩만 + var seen = Set() + self.todayMenus = meals.flatMap(\.displayMenus).filter { !$0.name.isEmpty && seen.insert($0.menuId).inserted } + self.hasLoadedTodayMenus = true + case .failure(let error): + print("오늘 식단 조회 실패 \(slot.restaurant.identifier)/\(slot.mealTime.rawValue): \(error.localizedDescription)") + self.todayMenus = [] + self.showToast(message: TextLiteral.Like.menuLoadFailed, type: .danger) + } + self.renderTodayMenuCard() + self.render() + } + } + + private func renderTodayMenuCard(selectedIds: Set? = nil) { + let favoriteIds = Set(MenuFavoriteManager.shared.favorites.map(\.menuId)) + let items = todayMenus.map { + MenuChipFlowView.Item(id: $0.menuId, title: $0.name, isLocked: favoriteIds.contains($0.menuId)) + } + todayMenuCard.configure( + slot: todaySlot, + items: items, + selectedIds: selectedIds ?? todayMenuCard.selectedIds, + showsNoMenu: hasLoadedTodayMenus + ) + } + + private func presentSlotSheet() { + let sheet = TodayMenuSlotSheetViewController(currentSlot: todaySlot) + sheet.onApply = { [weak self] slot in + guard let self else { return } + self.todaySlot = slot + self.todayMenus = [] + self.todayMenuCard.clearSelection() + self.renderTodayMenuCard() + self.loadTodayMenus() + } + present(sheet, animated: true) + } + + /// 선택한 메뉴를 한 번에 찜한다. 이미 찜한 메뉴는 칩에서 고를 수 없으므로 새 메뉴만 서버로 간다 + /// + /// 다른 곳(검색 결과 하트)에서 요청이 진행 중인 메뉴는 `setFavorite`가 completion 없이 돌아오므로 이번 제출에서 뺀다. + /// 실패한 메뉴는 선택을 남겨 두어 사용자가 다시 시도할 수 있게 한다 + private func submitTodayMenus() { + guard !isSubmittingTodayMenus else { return } + let manager = MenuFavoriteManager.shared + let selected = todayMenus.filter { + todayMenuCard.selectedIds.contains($0.menuId) && !manager.isPending(menuId: $0.menuId) + } + guard !selected.isEmpty else { return } + isSubmittingTodayMenus = true + + let restaurant = todaySlot.restaurant.identifier + let group = DispatchGroup() + var failedIds = Set() + for menu in selected { + group.enter() + manager.setFavorite(true, menuId: menu.menuId, menuName: menu.name, restaurant: restaurant) { result in + if case .failure(let error) = result { + failedIds.insert(menu.menuId) + print("오늘 식단 찜 실패 menuId=\(menu.menuId): \(error.localizedDescription)") + } + group.leave() + } + } + group.notify(queue: .main) { [weak self] in + guard let self else { return } + self.isSubmittingTodayMenus = false + self.renderTodayMenuCard(selectedIds: failedIds) + self.render() + if failedIds.isEmpty { + self.showToast(message: TextLiteral.Like.menuAddedToast, type: .success) + } else { + self.showToast(message: TextLiteral.Like.menuUpdateFailed, type: .danger) + } + } + } + // MARK: - Favorite private func toggleFavorite(at indexPath: IndexPath) { @@ -244,6 +435,8 @@ final class MenuLikeViewController: BaseViewController { guard menus.indices.contains(indexPath.row) else { return } let menu = menus[indexPath.row] item = (menu.menuId, menu.menuName, menu.restaurant, !manager.isFavorite(menu)) + case .searchIdle: + return } guard !manager.isPending(menuId: item.menuId) else { return } @@ -256,7 +449,8 @@ final class MenuLikeViewController: BaseViewController { guard let self else { return } switch result { case .success: - // 찜 목록에서 해제한 메뉴는 목록에서 바로 사라진다 + // 찜 목록에서 해제한 메뉴는 목록에서 바로 사라지고, 카드의 잠긴 칩도 풀린다 + self.renderTodayMenuCard() self.render() self.showToast( message: item.toBe ? TextLiteral.Like.menuAddedToast : TextLiteral.Like.menuRemovedToast, @@ -283,6 +477,8 @@ extension MenuLikeViewController: UITableViewDataSource { switch mode { case .favorites: MenuFavoriteManager.shared.favorites.count + case .searchIdle: + 0 case .search(_, let menus, _): menus.count } @@ -311,6 +507,8 @@ extension MenuLikeViewController: UITableViewDataSource { isFavorite: MenuFavoriteManager.shared.isFavorite(menu), style: .search(keyword: keyword) ) + case .searchIdle: + break } cell.onTapHeart = { [weak self, weak cell, weak tableView] in guard let self, let cell, let indexPath = tableView?.indexPath(for: cell) else { return } @@ -324,21 +522,35 @@ extension MenuLikeViewController: UITableViewDataSource { extension MenuLikeViewController: UITextFieldDelegate { + func textFieldDidBeginEditing(_ textField: UITextField) { + // 포커스가 가면 카드와 찜 목록을 숨긴다. 검색어가 이미 2글자 이상이면 결과는 그대로 둔다 + if currentKeyword.count < MenuFavoriteManager.minimumKeywordLength { + mode = .searchIdle + render() + } + } + + func textFieldDidEndEditing(_ textField: UITextField) { + // 결과가 떠 있으면 유지하고, 검색어가 짧으면 찜 목록으로 돌아간다 + if currentKeyword.count < MenuFavoriteManager.minimumKeywordLength { + finishSearch() + } + } + func textFieldShouldReturn(_ textField: UITextField) -> Bool { - textField.resignFirstResponder() // 1글자로 검색을 시도하면 2글자부터 검색된다는 것을 알린다 (빈 검색어는 키보드만 내린다) let length = currentKeyword.count if length > 0, length < MenuFavoriteManager.minimumKeywordLength { showToast(message: TextLiteral.Like.menuSearchTooShort, type: .danger) } + textField.resignFirstResponder() return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { - // X 버튼으로 지운 경우에도 editingChanged와 같은 흐름을 타도록 지워진 뒤 반영한다 - DispatchQueue.main.async { [weak self] in - self?.textDidChange() - } - return true + // X: 검색을 끝내고 이전 화면(카드가 접힌 찜 목록)으로 돌아간다 + textField.resignFirstResponder() + finishSearch() + return false } } diff --git a/EATSSU/App/Sources/Presentation/Like/ViewController/TodayMenuSlotSheetViewController.swift b/EATSSU/App/Sources/Presentation/Like/ViewController/TodayMenuSlotSheetViewController.swift new file mode 100644 index 00000000..21734d5c --- /dev/null +++ b/EATSSU/App/Sources/Presentation/Like/ViewController/TodayMenuSlotSheetViewController.swift @@ -0,0 +1,269 @@ +// +// TodayMenuSlotSheetViewController.swift +// EATSSU +// +// Created by 황상환 on 11/8/26. +// + +import UIKit + +import SnapKit + +import EATSSUDesign + +/// "오늘 식단에서 찜하기"의 식당·시간대를 바꾸는 바텀시트 +/// +/// 디자인(390 기준): 높이 360, 손잡이 30×2(위 14), 제목 Bold 16(위 33), 구역 제목 SemiBold 16 +/// 칩 높이 36 · 간격 5 · 폭 균등, 적용하기 52(좌우 24, 모서리 12, 안전 영역 바닥) +/// 식당마다 운영하지 않는 시간대는 비활성(gray100 배경, gray300 글자). 식당과 시간대를 모두 고르고 +/// 현재 값과 다를 때만 적용하기가 켜진다 +final class TodayMenuSlotSheetViewController: UIViewController { + + // MARK: - Constants + + static let preferredHeight: CGFloat = 360 + + private enum Layout { + static let horizontalInset: CGFloat = 24 + static let grabberTop: CGFloat = 14 + static let grabberSize = CGSize(width: 30, height: 2) + static let titleTop: CGFloat = 33 + static let restaurantLabelTop: CGFloat = 77 + static let chipsTop: CGFloat = 15 + static let chipHeight: CGFloat = 36 + static let chipSpacing: CGFloat = 5 + static let mealTimeLabelTop: CGFloat = 15 + static let applyHeight: CGFloat = 52 + static let applyCornerRadius: CGFloat = 12 + static let disabledAlpha: CGFloat = 0.5 + } + + // MARK: - Properties + + var onApply: ((TodayMenuSlot) -> Void)? + + private let currentSlot: TodayMenuSlot + private var selectedRestaurant: Restaurant? + private var selectedMealTime: MealTimePart? + + // MARK: - UI Components + + private let grabberView = UIView() + private let titleLabel = UILabel() + private let restaurantLabel = UILabel() + private let restaurantStackView = UIStackView() + private let mealTimeLabel = UILabel() + private let mealTimeStackView = UIStackView() + private let applyButton = UIButton(type: .custom) + + private var restaurantChips: [UIButton] = [] + private var mealTimeChips: [UIButton] = [] + + // MARK: - Init + + init(currentSlot: TodayMenuSlot) { + self.currentSlot = currentSlot + self.selectedRestaurant = currentSlot.restaurant + self.selectedMealTime = currentSlot.mealTime + super.init(nibName: nil, bundle: nil) + modalPresentationStyle = .pageSheet + if let sheet = sheetPresentationController { + if #available(iOS 16.0, *) { + // 디자인 높이 360은 홈 인디케이터 영역을 포함한 값이고, 커스텀 detent는 안전 영역을 뺀 높이라서 보정한다 + sheet.detents = [.custom { _ in + let bottomInset = UIApplication.shared.connectedScenes + .compactMap { ($0 as? UIWindowScene)?.keyWindow } + .first?.safeAreaInsets.bottom ?? 0 + return Self.preferredHeight - bottomInset + }] + } else { + sheet.detents = [.medium()] + } + sheet.prefersGrabberVisible = false + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - Life Cycle + + override func viewDidLoad() { + super.viewDidLoad() + configureUI() + setLayout() + applySelection() + } + + // MARK: - View Setup + + private func configureUI() { + view.backgroundColor = .white + + grabberView.backgroundColor = .gray400 + grabberView.layer.cornerRadius = Layout.grabberSize.height / 2 + + titleLabel.text = TextLiteral.Like.slotSheetTitle + titleLabel.font = .subtitle1 + titleLabel.textColor = .gray700 + titleLabel.textAlignment = .center + + restaurantLabel.text = TextLiteral.Like.restaurantSection + restaurantLabel.font = .subtitle2 + restaurantLabel.textColor = .gray700 + + mealTimeLabel.text = TextLiteral.Like.mealTimeSection + mealTimeLabel.font = .subtitle2 + mealTimeLabel.textColor = .gray700 + + [restaurantStackView, mealTimeStackView].forEach { + $0.axis = .horizontal + $0.spacing = Layout.chipSpacing + $0.distribution = .fillEqually + } + + restaurantChips = TodayMenuSlot.selectableRestaurants.enumerated().map { index, restaurant in + let chip = makeChip(title: restaurant.shortTitle, tag: index) + chip.addTarget(self, action: #selector(didTapRestaurant(_:)), for: .touchUpInside) + restaurantStackView.addArrangedSubview(chip) + return chip + } + mealTimeChips = MealTimePart.allCases.enumerated().map { index, mealTime in + let chip = makeChip(title: mealTime.title, tag: index) + chip.addTarget(self, action: #selector(didTapMealTime(_:)), for: .touchUpInside) + mealTimeStackView.addArrangedSubview(chip) + return chip + } + + applyButton.setTitle(TextLiteral.Like.apply, for: .normal) + applyButton.titleLabel?.font = .subtitle1 + applyButton.setTitleColor(.white, for: .normal) + applyButton.backgroundColor = .primary + applyButton.layer.cornerRadius = Layout.applyCornerRadius + applyButton.addTarget(self, action: #selector(didTapApply), for: .touchUpInside) + + view.addSubviews(grabberView, titleLabel, restaurantLabel, restaurantStackView, mealTimeLabel, mealTimeStackView, applyButton) + } + + private func setLayout() { + grabberView.snp.makeConstraints { + $0.top.equalToSuperview().offset(Layout.grabberTop) + $0.centerX.equalToSuperview() + $0.size.equalTo(Layout.grabberSize) + } + titleLabel.snp.makeConstraints { + $0.top.equalToSuperview().offset(Layout.titleTop) + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + } + restaurantLabel.snp.makeConstraints { + $0.top.equalToSuperview().offset(Layout.restaurantLabelTop) + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + } + restaurantStackView.snp.makeConstraints { + $0.top.equalTo(restaurantLabel.snp.bottom).offset(Layout.chipsTop) + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + $0.height.equalTo(Layout.chipHeight) + } + mealTimeLabel.snp.makeConstraints { + $0.top.equalTo(restaurantStackView.snp.bottom).offset(Layout.mealTimeLabelTop) + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + } + mealTimeStackView.snp.makeConstraints { + $0.top.equalTo(mealTimeLabel.snp.bottom).offset(Layout.chipsTop) + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + $0.height.equalTo(Layout.chipHeight) + } + applyButton.snp.makeConstraints { + $0.leading.trailing.equalToSuperview().inset(Layout.horizontalInset) + $0.height.equalTo(Layout.applyHeight) + $0.bottom.equalTo(view.safeAreaLayoutGuide) + } + } + + private func makeChip(title: String, tag: Int) -> UIButton { + let chip = UIButton(type: .custom) + chip.setTitle(title, for: .normal) + chip.titleLabel?.font = .body2 + chip.titleLabel?.adjustsFontSizeToFitWidth = true + chip.titleLabel?.minimumScaleFactor = 0.7 + chip.layer.cornerRadius = Layout.chipHeight / 2 + chip.layer.borderWidth = 1 + chip.tag = tag + return chip + } + + // MARK: - Selection + + @objc private func didTapRestaurant(_ sender: UIButton) { + let restaurant = TodayMenuSlot.selectableRestaurants[sender.tag] + selectedRestaurant = restaurant + // 새 식당이 운영하지 않는 시간대가 골라져 있으면 시간대를 다시 고르게 한다 + if let mealTime = selectedMealTime, !TodayMenuSlot.isAvailable(restaurant: restaurant, mealTime: mealTime) { + selectedMealTime = nil + } + applySelection() + } + + @objc private func didTapMealTime(_ sender: UIButton) { + let mealTime = MealTimePart.allCases[sender.tag] + if let restaurant = selectedRestaurant, !TodayMenuSlot.isAvailable(restaurant: restaurant, mealTime: mealTime) { + return + } + selectedMealTime = mealTime + applySelection() + } + + @objc private func didTapApply() { + guard let restaurant = selectedRestaurant, let mealTime = selectedMealTime else { return } + let slot = TodayMenuSlot(restaurant: restaurant, mealTime: mealTime) + dismiss(animated: true) { [onApply] in + onApply?(slot) + } + } + + private func applySelection() { + for (chip, restaurant) in zip(restaurantChips, TodayMenuSlot.selectableRestaurants) { + style(chip, state: restaurant == selectedRestaurant ? .selected : .normal) + } + for (chip, mealTime) in zip(mealTimeChips, MealTimePart.allCases) { + let isAvailable = selectedRestaurant.map { TodayMenuSlot.isAvailable(restaurant: $0, mealTime: mealTime) } ?? true + let state: ChipState = !isAvailable ? .unavailable : (mealTime == selectedMealTime ? .selected : .normal) + style(chip, state: state) + } + let selected = zip(selectedRestaurant, selectedMealTime).map { TodayMenuSlot(restaurant: $0, mealTime: $1) } + let canApply = selected != nil && selected != currentSlot + applyButton.isEnabled = canApply + applyButton.alpha = canApply ? 1 : Layout.disabledAlpha + } + + private enum ChipState { + case normal, selected, unavailable + } + + private func style(_ chip: UIButton, state: ChipState) { + switch state { + case .normal: + chip.backgroundColor = .white + chip.layer.borderColor = UIColor.gray300.cgColor + chip.setTitleColor(.gray500, for: .normal) + chip.isEnabled = true + case .selected: + chip.backgroundColor = .primary + chip.layer.borderColor = UIColor.primary.cgColor + chip.setTitleColor(.white, for: .normal) + chip.isEnabled = true + case .unavailable: + chip.backgroundColor = .gray100 + chip.layer.borderColor = UIColor.gray100.cgColor + chip.setTitleColor(.gray300, for: .disabled) + chip.isEnabled = false + } + } +} + +private func zip(_ a: A?, _ b: B?) -> (A, B)? { + guard let a, let b else { return nil } + return (a, b) +} diff --git a/EATSSU/App/Sources/Utility/Extension/DateFormatter+.swift b/EATSSU/App/Sources/Utility/Extension/DateFormatter+.swift new file mode 100644 index 00000000..de0ab592 --- /dev/null +++ b/EATSSU/App/Sources/Utility/Extension/DateFormatter+.swift @@ -0,0 +1,21 @@ +// +// DateFormatter+.swift +// EATSSU +// +// Created by 황상환 on 11/8/26. +// + +import Foundation + +extension DateFormatter { + /// 서버 식단 날짜 형식 `yyyyMMdd` (학식 조회 · 푸시 `date` · 오늘 식단 찜하기 공용) + /// 사용자 달력·로케일 설정에 영향받지 않도록 그레고리력 · en_US_POSIX로 고정하고, 날짜 경계는 기기 시간대를 따른다 + static let serverDay: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = .current + formatter.dateFormat = "yyyyMMdd" + return formatter + }() +} diff --git a/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift b/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift index 2b7c5357..b40c3560 100644 --- a/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift +++ b/EATSSU/App/Sources/Utility/Literal/TextLiteral.swift @@ -1304,6 +1304,11 @@ enum TextLiteral { static var facultyRestaurant: String { Localization.localized("restaurant.facultyRestaurant", fallback: "FACULTY (교직원 전용)") } + + /// "교직원 식당" (칩 등 좁은 곳) + static var facultyRestaurantShort: String { + Localization.localized("restaurant.facultyRestaurantShort", fallback: "교직원 식당") + } } // MARK: - Academic @@ -1517,5 +1522,52 @@ enum TextLiteral { static var menuSearchTooShort: String { Localization.localized("like.menuSearchTooShort", fallback: "2글자 이상 입력해주세요.") } + + // MARK: 오늘 식단에서 찜하기 + + /// "오늘 식단에서 찜하기" + static var todayMenuToggle: String { + Localization.localized("like.todayMenuToggle", fallback: "오늘 식단에서 찜하기") + } + + /// "메뉴를 선택해 찜할 수 있어요." + static var todayMenuHint: String { + Localization.localized("like.todayMenuHint", fallback: "메뉴를 선택해 찜할 수 있어요.") + } + + /// "변경" + static var change: String { + Localization.localized("like.change", fallback: "변경") + } + + /// "메뉴 찜하기" (선택 없음) + static var favoriteMenus: String { + Localization.localized("like.favoriteMenus", fallback: "메뉴 찜하기") + } + + /// "선택한 %d개 메뉴 찜하기" + static func favoriteSelectedMenus(_ count: Int) -> String { + Localization.formatted("like.favoriteSelectedMenus", fallback: "선택한 %d개 메뉴 찜하기", count) + } + + /// "메뉴 변경" (바텀시트 제목) + static var slotSheetTitle: String { + Localization.localized("like.slotSheetTitle", fallback: "메뉴 변경") + } + + /// "식당 종류" + static var restaurantSection: String { + Localization.localized("like.restaurantSection", fallback: "식당 종류") + } + + /// "시간대" + static var mealTimeSection: String { + Localization.localized("like.mealTimeSection", fallback: "시간대") + } + + /// "적용하기" + static var apply: String { + Localization.localized("like.apply", fallback: "적용하기") + } } } diff --git a/EATSSU/Tests/UnitTests/TodayMenuSlotTests.swift b/EATSSU/Tests/UnitTests/TodayMenuSlotTests.swift new file mode 100644 index 00000000..7f4fc21a --- /dev/null +++ b/EATSSU/Tests/UnitTests/TodayMenuSlotTests.swift @@ -0,0 +1,39 @@ +// +// TodayMenuSlotTests.swift +// EATSSUUnitTests +// +// Created by 황상환 on 11/8/26. +// + +import XCTest + +@testable import EATSSU_DEV + +/// "오늘 식단에서 찜하기" 식당·시간대 규칙 (기능 명세) +final class TodayMenuSlotTests: XCTestCase { + + func test_기본값은_학생식당_점심() { + XCTAssertEqual(TodayMenuSlot.default, TodayMenuSlot(restaurant: .studentRestaurant, mealTime: .lunch)) + } + + func test_고를_수_있는_식당은_4곳이고_스낵코너는_없다() { + XCTAssertEqual(TodayMenuSlot.selectableRestaurants.count, 4) + XCTAssertFalse(TodayMenuSlot.selectableRestaurants.contains(.snackCorner)) + } + + func test_식당별_미운영_시간대() { + XCTAssertFalse(TodayMenuSlot.isAvailable(restaurant: .studentRestaurant, mealTime: .dinner)) + XCTAssertTrue(TodayMenuSlot.isAvailable(restaurant: .studentRestaurant, mealTime: .morning)) + XCTAssertFalse(TodayMenuSlot.isAvailable(restaurant: .dodamRestaurant, mealTime: .morning)) + XCTAssertTrue(TodayMenuSlot.isAvailable(restaurant: .dodamRestaurant, mealTime: .dinner)) + XCTAssertFalse(TodayMenuSlot.isAvailable(restaurant: .dormitoryRestaurant, mealTime: .morning)) + XCTAssertFalse(TodayMenuSlot.isAvailable(restaurant: .facultyRestaurant, mealTime: .morning)) + XCTAssertFalse(TodayMenuSlot.isAvailable(restaurant: .facultyRestaurant, mealTime: .dinner)) + XCTAssertTrue(TodayMenuSlot.isAvailable(restaurant: .facultyRestaurant, mealTime: .lunch)) + } + + func test_시간대_탭_인덱스와_서버_값() { + XCTAssertEqual(MealTimePart(rawValue: "LUNCH")?.tabIndex, 1) + XCTAssertEqual(MealTimePart.allCases.map(\.tabIndex), [0, 1, 2]) + } +} diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_calendar.imageset/Contents.json b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_calendar.imageset/Contents.json new file mode 100644 index 00000000..fab31fc2 --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_calendar.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "ic_calendar.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_calendar.imageset/ic_calendar.svg b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_calendar.imageset/ic_calendar.svg new file mode 100644 index 00000000..4869db05 --- /dev/null +++ b/EATSSUDesign/EATSSUDesign/Resources/Images.xcassets/ic_calendar.imageset/ic_calendar.svg @@ -0,0 +1,5 @@ + + + + +