restore: original UI views from first build, keep fixed models/API
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import Foundation
|
||||
|
||||
struct FitnessAPI {
|
||||
private let api = APIClient.shared
|
||||
|
||||
// MARK: - Entries
|
||||
|
||||
func getEntries(date: String) async throws -> [FoodEntry] {
|
||||
try await api.get(
|
||||
"/api/fitness/entries",
|
||||
queryItems: [URLQueryItem(name: "date", value: date)]
|
||||
)
|
||||
}
|
||||
|
||||
func createEntry(_ request: CreateEntryRequest) async throws -> FoodEntry {
|
||||
try await api.post("/api/fitness/entries", body: request)
|
||||
}
|
||||
|
||||
func updateEntry(id: String, request: UpdateEntryRequest) async throws -> FoodEntry {
|
||||
try await api.patch("/api/fitness/entries/\(id)", body: request)
|
||||
}
|
||||
|
||||
func deleteEntry(id: String) async throws {
|
||||
try await api.delete("/api/fitness/entries/\(id)")
|
||||
}
|
||||
|
||||
// MARK: - Foods
|
||||
|
||||
func getFoods(limit: Int = 100) async throws -> [FoodItem] {
|
||||
try await api.get(
|
||||
"/api/fitness/foods",
|
||||
queryItems: [URLQueryItem(name: "limit", value: "\(limit)")]
|
||||
)
|
||||
}
|
||||
|
||||
func searchFoods(query: String, limit: Int = 20) async throws -> [FoodItem] {
|
||||
try await api.get(
|
||||
"/api/fitness/foods/search",
|
||||
queryItems: [
|
||||
URLQueryItem(name: "q", value: query),
|
||||
URLQueryItem(name: "limit", value: "\(limit)")
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
func getFood(id: String) async throws -> FoodItem {
|
||||
try await api.get("/api/fitness/foods/\(id)")
|
||||
}
|
||||
|
||||
func getRecentFoods(limit: Int = 8) async throws -> [FoodItem] {
|
||||
try await api.get(
|
||||
"/api/fitness/foods/recent",
|
||||
queryItems: [URLQueryItem(name: "limit", value: "\(limit)")]
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Goals
|
||||
|
||||
func getGoals(date: String) async throws -> DailyGoal {
|
||||
try await api.get(
|
||||
"/api/fitness/goals/for-date",
|
||||
queryItems: [URLQueryItem(name: "date", value: date)]
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Templates
|
||||
|
||||
func getTemplates() async throws -> [MealTemplate] {
|
||||
try await api.get("/api/fitness/templates")
|
||||
}
|
||||
|
||||
func logTemplate(id: String, date: String) async throws {
|
||||
try await api.postVoid(
|
||||
"/api/fitness/templates/\(id)/log",
|
||||
queryItems: [URLQueryItem(name: "date", value: date)]
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - AI Split
|
||||
|
||||
func splitFood(text: String, mealType: String) async throws -> [FoodItem] {
|
||||
let request = SplitFoodRequest(text: text, mealType: mealType)
|
||||
return try await api.post("/api/fitness/foods/split", body: request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import Foundation
|
||||
|
||||
struct FoodEntry: Codable, Identifiable, Hashable {
|
||||
let id: String
|
||||
let foodName: String
|
||||
let servingDescription: String?
|
||||
let quantity: Double
|
||||
let unit: String
|
||||
let mealType: String
|
||||
let calories: Double
|
||||
let protein: Double
|
||||
let carbs: Double
|
||||
let fat: Double
|
||||
let sugar: Double?
|
||||
let fiber: Double?
|
||||
let entryType: String?
|
||||
let method: String?
|
||||
let foodId: String?
|
||||
let imageUrl: String?
|
||||
let note: String?
|
||||
let loggedAt: String?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, quantity, unit, calories, protein, carbs, fat, sugar, fiber, note, method
|
||||
case foodName = "food_name"
|
||||
case servingDescription = "serving_description"
|
||||
case mealType = "meal_type"
|
||||
case entryType = "entry_type"
|
||||
case foodId = "food_id"
|
||||
case imageUrl = "image_url"
|
||||
case loggedAt = "logged_at"
|
||||
}
|
||||
|
||||
/// Alternate keys from the snapshot-based API response
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: FlexibleCodingKeys.self)
|
||||
|
||||
id = try container.decode(String.self, forKey: .init("id"))
|
||||
quantity = try container.decodeIfPresent(Double.self, forKey: .init("quantity")) ?? 1
|
||||
unit = try container.decodeIfPresent(String.self, forKey: .init("unit")) ?? "serving"
|
||||
mealType = try container.decodeIfPresent(String.self, forKey: .init("meal_type")) ?? "snack"
|
||||
|
||||
// Handle both "food_name" and "snapshot_food_name"
|
||||
if let name = try container.decodeIfPresent(String.self, forKey: .init("food_name")) {
|
||||
foodName = name
|
||||
} else if let name = try container.decodeIfPresent(String.self, forKey: .init("snapshot_food_name")) {
|
||||
foodName = name
|
||||
} else {
|
||||
foodName = "Unknown"
|
||||
}
|
||||
|
||||
servingDescription = try container.decodeIfPresent(String.self, forKey: .init("serving_description"))
|
||||
?? container.decodeIfPresent(String.self, forKey: .init("snapshot_serving_label"))
|
||||
|
||||
// Handle both direct and snapshot_ prefixed fields
|
||||
calories = try container.decodeIfPresent(Double.self, forKey: .init("calories"))
|
||||
?? container.decodeIfPresent(Double.self, forKey: .init("snapshot_calories"))
|
||||
?? 0
|
||||
protein = try container.decodeIfPresent(Double.self, forKey: .init("protein"))
|
||||
?? container.decodeIfPresent(Double.self, forKey: .init("snapshot_protein"))
|
||||
?? 0
|
||||
carbs = try container.decodeIfPresent(Double.self, forKey: .init("carbs"))
|
||||
?? container.decodeIfPresent(Double.self, forKey: .init("snapshot_carbs"))
|
||||
?? 0
|
||||
fat = try container.decodeIfPresent(Double.self, forKey: .init("fat"))
|
||||
?? container.decodeIfPresent(Double.self, forKey: .init("snapshot_fat"))
|
||||
?? 0
|
||||
sugar = try container.decodeIfPresent(Double.self, forKey: .init("sugar"))
|
||||
?? container.decodeIfPresent(Double.self, forKey: .init("snapshot_sugar"))
|
||||
fiber = try container.decodeIfPresent(Double.self, forKey: .init("fiber"))
|
||||
?? container.decodeIfPresent(Double.self, forKey: .init("snapshot_fiber"))
|
||||
|
||||
entryType = try container.decodeIfPresent(String.self, forKey: .init("entry_type"))
|
||||
method = try container.decodeIfPresent(String.self, forKey: .init("entry_method"))
|
||||
?? container.decodeIfPresent(String.self, forKey: .init("method"))
|
||||
foodId = try container.decodeIfPresent(String.self, forKey: .init("food_id"))
|
||||
imageUrl = try container.decodeIfPresent(String.self, forKey: .init("image_url"))
|
||||
?? container.decodeIfPresent(String.self, forKey: .init("food_image_path"))
|
||||
note = try container.decodeIfPresent(String.self, forKey: .init("note"))
|
||||
loggedAt = try container.decodeIfPresent(String.self, forKey: .init("logged_at"))
|
||||
?? container.decodeIfPresent(String.self, forKey: .init("created_at"))
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(id, forKey: .id)
|
||||
try container.encode(foodName, forKey: .foodName)
|
||||
try container.encodeIfPresent(servingDescription, forKey: .servingDescription)
|
||||
try container.encode(quantity, forKey: .quantity)
|
||||
try container.encode(unit, forKey: .unit)
|
||||
try container.encode(mealType, forKey: .mealType)
|
||||
try container.encode(calories, forKey: .calories)
|
||||
try container.encode(protein, forKey: .protein)
|
||||
try container.encode(carbs, forKey: .carbs)
|
||||
try container.encode(fat, forKey: .fat)
|
||||
try container.encodeIfPresent(sugar, forKey: .sugar)
|
||||
try container.encodeIfPresent(fiber, forKey: .fiber)
|
||||
try container.encodeIfPresent(entryType, forKey: .entryType)
|
||||
try container.encodeIfPresent(method, forKey: .method)
|
||||
try container.encodeIfPresent(foodId, forKey: .foodId)
|
||||
try container.encodeIfPresent(imageUrl, forKey: .imageUrl)
|
||||
try container.encodeIfPresent(note, forKey: .note)
|
||||
try container.encodeIfPresent(loggedAt, forKey: .loggedAt)
|
||||
}
|
||||
|
||||
static func == (lhs: FoodEntry, rhs: FoodEntry) -> Bool {
|
||||
lhs.id == rhs.id
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Flexible coding keys for handling multiple API shapes
|
||||
struct FlexibleCodingKeys: CodingKey {
|
||||
var stringValue: String
|
||||
var intValue: Int?
|
||||
|
||||
init(_ string: String) {
|
||||
self.stringValue = string
|
||||
self.intValue = nil
|
||||
}
|
||||
|
||||
init?(stringValue: String) {
|
||||
self.stringValue = stringValue
|
||||
self.intValue = nil
|
||||
}
|
||||
|
||||
init?(intValue: Int) {
|
||||
self.stringValue = "\(intValue)"
|
||||
self.intValue = intValue
|
||||
}
|
||||
}
|
||||
|
||||
struct FoodItem: Codable, Identifiable {
|
||||
let id: String
|
||||
let name: String
|
||||
let brand: String?
|
||||
let baseUnit: String?
|
||||
let caloriesPerBase: Double
|
||||
let proteinPerBase: Double?
|
||||
let carbsPerBase: Double?
|
||||
let fatPerBase: Double?
|
||||
let sugarPerBase: Double?
|
||||
let fiberPerBase: Double?
|
||||
let status: String?
|
||||
let imageUrl: String?
|
||||
let favorite: Bool?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, name, brand, status, favorite
|
||||
case baseUnit = "base_unit"
|
||||
case caloriesPerBase = "calories_per_base"
|
||||
case proteinPerBase = "protein_per_base"
|
||||
case carbsPerBase = "carbs_per_base"
|
||||
case fatPerBase = "fat_per_base"
|
||||
case sugarPerBase = "sugar_per_base"
|
||||
case fiberPerBase = "fiber_per_base"
|
||||
case imageUrl = "image_url"
|
||||
}
|
||||
|
||||
var displayUnit: String {
|
||||
baseUnit ?? "serving"
|
||||
}
|
||||
|
||||
var displayInfo: String {
|
||||
let parts = [brand].compactMap { $0 }
|
||||
let prefix = parts.isEmpty ? "" : "\(parts.joined(separator: " ")) - "
|
||||
return "\(prefix)\(displayUnit)"
|
||||
}
|
||||
|
||||
func scaledCalories(quantity: Double) -> Double {
|
||||
caloriesPerBase * quantity
|
||||
}
|
||||
|
||||
func scaledProtein(quantity: Double) -> Double {
|
||||
(proteinPerBase ?? 0) * quantity
|
||||
}
|
||||
|
||||
func scaledCarbs(quantity: Double) -> Double {
|
||||
(carbsPerBase ?? 0) * quantity
|
||||
}
|
||||
|
||||
func scaledFat(quantity: Double) -> Double {
|
||||
(fatPerBase ?? 0) * quantity
|
||||
}
|
||||
}
|
||||
|
||||
struct DailyGoal: Codable {
|
||||
let calories: Double
|
||||
let protein: Double
|
||||
let carbs: Double
|
||||
let fat: Double
|
||||
let sugar: Double?
|
||||
let fiber: Double?
|
||||
|
||||
static let defaultGoal = DailyGoal(
|
||||
calories: 2000, protein: 150, carbs: 200, fat: 65, sugar: 50, fiber: 30
|
||||
)
|
||||
}
|
||||
|
||||
struct MealTemplate: Codable, Identifiable {
|
||||
let id: String
|
||||
let name: String
|
||||
let mealType: String
|
||||
let calories: Double
|
||||
let protein: Double?
|
||||
let carbs: Double?
|
||||
let fat: Double?
|
||||
let itemsCount: Int?
|
||||
|
||||
// Support flexible decoding for templates with nested items
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, name, calories, protein, carbs, fat, items
|
||||
case mealType = "meal_type"
|
||||
case itemsCount = "items_count"
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
id = try container.decode(String.self, forKey: .id)
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
mealType = try container.decodeIfPresent(String.self, forKey: .mealType) ?? "snack"
|
||||
protein = try container.decodeIfPresent(Double.self, forKey: .protein)
|
||||
carbs = try container.decodeIfPresent(Double.self, forKey: .carbs)
|
||||
fat = try container.decodeIfPresent(Double.self, forKey: .fat)
|
||||
|
||||
// Try direct calories first, then compute from items
|
||||
if let directCals = try? container.decode(Double.self, forKey: .calories) {
|
||||
calories = directCals
|
||||
itemsCount = try container.decodeIfPresent(Int.self, forKey: .itemsCount)
|
||||
} else if let items = try? container.decode([TemplateItem].self, forKey: .items) {
|
||||
calories = items.reduce(0) { $0 + ($1.snapshotCalories ?? 0) * ($1.quantity ?? 1) }
|
||||
itemsCount = items.count
|
||||
} else {
|
||||
calories = 0
|
||||
itemsCount = try container.decodeIfPresent(Int.self, forKey: .itemsCount)
|
||||
}
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(id, forKey: .id)
|
||||
try container.encode(name, forKey: .name)
|
||||
try container.encode(mealType, forKey: .mealType)
|
||||
try container.encode(calories, forKey: .calories)
|
||||
try container.encodeIfPresent(protein, forKey: .protein)
|
||||
try container.encodeIfPresent(carbs, forKey: .carbs)
|
||||
try container.encodeIfPresent(fat, forKey: .fat)
|
||||
try container.encodeIfPresent(itemsCount, forKey: .itemsCount)
|
||||
}
|
||||
}
|
||||
|
||||
private struct TemplateItem: Codable {
|
||||
let snapshotCalories: Double?
|
||||
let quantity: Double?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case snapshotCalories = "snapshot_calories"
|
||||
case quantity
|
||||
}
|
||||
}
|
||||
|
||||
struct CreateEntryRequest: Encodable {
|
||||
let foodId: String
|
||||
let quantity: Double
|
||||
let unit: String
|
||||
let mealType: String
|
||||
let entryDate: String
|
||||
let entryMethod: String
|
||||
let source: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case quantity, unit, source
|
||||
case foodId = "food_id"
|
||||
case mealType = "meal_type"
|
||||
case entryDate = "entry_date"
|
||||
case entryMethod = "entry_method"
|
||||
}
|
||||
}
|
||||
|
||||
struct UpdateEntryRequest: Encodable {
|
||||
var quantity: Double?
|
||||
var unit: String?
|
||||
var mealType: String?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case quantity, unit
|
||||
case mealType = "meal_type"
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitFoodRequest: Encodable {
|
||||
let text: String
|
||||
let mealType: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case text
|
||||
case mealType = "meal_type"
|
||||
}
|
||||
}
|
||||
|
||||
// Meals enum for type safety
|
||||
enum MealType: String, CaseIterable, Identifiable {
|
||||
case breakfast
|
||||
case lunch
|
||||
case dinner
|
||||
case snack
|
||||
|
||||
var id: String { rawValue }
|
||||
|
||||
var displayName: String {
|
||||
rawValue.capitalized
|
||||
}
|
||||
|
||||
var icon: String {
|
||||
switch self {
|
||||
case .breakfast: return "sunrise.fill"
|
||||
case .lunch: return "sun.max.fill"
|
||||
case .dinner: return "moon.fill"
|
||||
case .snack: return "leaf.fill"
|
||||
}
|
||||
}
|
||||
|
||||
static func guess() -> MealType {
|
||||
let hour = Calendar.current.component(.hour, from: Date())
|
||||
switch hour {
|
||||
case 5..<11: return .breakfast
|
||||
case 11..<15: return .lunch
|
||||
case 15..<20: return .dinner
|
||||
default: return .snack
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper for grouping entries by meal
|
||||
struct MealGroup: Identifiable {
|
||||
let meal: MealType
|
||||
let entries: [FoodEntry]
|
||||
|
||||
var id: String { meal.rawValue }
|
||||
|
||||
var totalCalories: Double {
|
||||
entries.reduce(0) { $0 + $1.calories }
|
||||
}
|
||||
|
||||
var totalProtein: Double {
|
||||
entries.reduce(0) { $0 + $1.protein }
|
||||
}
|
||||
|
||||
var totalCarbs: Double {
|
||||
entries.reduce(0) { $0 + $1.carbs }
|
||||
}
|
||||
|
||||
var totalFat: Double {
|
||||
entries.reduce(0) { $0 + $1.fat }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor @Observable
|
||||
final class FitnessRepository {
|
||||
static let shared = FitnessRepository()
|
||||
|
||||
private let api = FitnessAPI()
|
||||
|
||||
// Cached data
|
||||
var cachedFoods: [FoodItem] = []
|
||||
var cachedRecentFoods: [FoodItem] = []
|
||||
var cachedTemplates: [MealTemplate] = []
|
||||
var cachedGoals: [String: DailyGoal] = [:]
|
||||
var cachedEntries: [String: [FoodEntry]] = [:]
|
||||
|
||||
private init() {}
|
||||
|
||||
// MARK: - Entries
|
||||
|
||||
func entries(for date: String, forceRefresh: Bool = false) async throws -> [FoodEntry] {
|
||||
if !forceRefresh, let cached = cachedEntries[date] {
|
||||
return cached
|
||||
}
|
||||
let entries = try await api.getEntries(date: date)
|
||||
cachedEntries[date] = entries
|
||||
return entries
|
||||
}
|
||||
|
||||
func createEntry(_ request: CreateEntryRequest) async throws -> FoodEntry {
|
||||
let entry = try await api.createEntry(request)
|
||||
// Invalidate cache for that date
|
||||
cachedEntries[request.entryDate] = nil
|
||||
return entry
|
||||
}
|
||||
|
||||
func updateEntry(id: String, request: UpdateEntryRequest, date: String) async throws -> FoodEntry {
|
||||
let entry = try await api.updateEntry(id: id, request: request)
|
||||
cachedEntries[date] = nil
|
||||
return entry
|
||||
}
|
||||
|
||||
func deleteEntry(id: String, date: String) async throws {
|
||||
try await api.deleteEntry(id: id)
|
||||
cachedEntries[date] = nil
|
||||
}
|
||||
|
||||
// MARK: - Foods
|
||||
|
||||
func allFoods(forceRefresh: Bool = false) async throws -> [FoodItem] {
|
||||
if !forceRefresh, !cachedFoods.isEmpty {
|
||||
return cachedFoods
|
||||
}
|
||||
cachedFoods = try await api.getFoods()
|
||||
return cachedFoods
|
||||
}
|
||||
|
||||
func searchFoods(query: String) async throws -> [FoodItem] {
|
||||
try await api.searchFoods(query: query)
|
||||
}
|
||||
|
||||
func recentFoods(forceRefresh: Bool = false) async throws -> [FoodItem] {
|
||||
if !forceRefresh, !cachedRecentFoods.isEmpty {
|
||||
return cachedRecentFoods
|
||||
}
|
||||
cachedRecentFoods = try await api.getRecentFoods()
|
||||
return cachedRecentFoods
|
||||
}
|
||||
|
||||
// MARK: - Goals
|
||||
|
||||
func goals(for date: String, forceRefresh: Bool = false) async throws -> DailyGoal {
|
||||
if !forceRefresh, let cached = cachedGoals[date] {
|
||||
return cached
|
||||
}
|
||||
let goal = try await api.getGoals(date: date)
|
||||
cachedGoals[date] = goal
|
||||
return goal
|
||||
}
|
||||
|
||||
// MARK: - Templates
|
||||
|
||||
func templates(forceRefresh: Bool = false) async throws -> [MealTemplate] {
|
||||
if !forceRefresh, !cachedTemplates.isEmpty {
|
||||
return cachedTemplates
|
||||
}
|
||||
cachedTemplates = try await api.getTemplates()
|
||||
return cachedTemplates
|
||||
}
|
||||
|
||||
func logTemplate(id: String, date: String) async throws {
|
||||
try await api.logTemplate(id: id, date: date)
|
||||
cachedEntries[date] = nil
|
||||
}
|
||||
|
||||
// MARK: - Invalidation
|
||||
|
||||
func invalidateAll() {
|
||||
cachedFoods = []
|
||||
cachedRecentFoods = []
|
||||
cachedTemplates = []
|
||||
cachedGoals = [:]
|
||||
cachedEntries = [:]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor @Observable
|
||||
final class FoodSearchViewModel {
|
||||
var searchText = ""
|
||||
var searchResults: [FoodItem] = []
|
||||
var recentFoods: [FoodItem] = []
|
||||
var isSearching = false
|
||||
var isLoadingRecent = false
|
||||
var errorMessage: String?
|
||||
|
||||
// Add food sheet state
|
||||
var selectedFood: FoodItem?
|
||||
var showAddSheet = false
|
||||
var addQuantity: Double = 1
|
||||
var addMealType: MealType = .guess()
|
||||
var isAddingFood = false
|
||||
|
||||
private let repo = FitnessRepository.shared
|
||||
private var searchTask: Task<Void, Never>?
|
||||
|
||||
var displayedFoods: [FoodItem] {
|
||||
if searchText.trimmingCharacters(in: .whitespaces).isEmpty {
|
||||
return recentFoods
|
||||
}
|
||||
return searchResults
|
||||
}
|
||||
|
||||
var isShowingRecent: Bool {
|
||||
searchText.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
|
||||
func loadRecent() async {
|
||||
isLoadingRecent = true
|
||||
do {
|
||||
recentFoods = try await repo.recentFoods(forceRefresh: true)
|
||||
} catch {
|
||||
// Silent failure for recent foods
|
||||
}
|
||||
isLoadingRecent = false
|
||||
}
|
||||
|
||||
func search() {
|
||||
let query = searchText.trimmingCharacters(in: .whitespaces)
|
||||
|
||||
// Cancel previous search
|
||||
searchTask?.cancel()
|
||||
|
||||
guard !query.isEmpty else {
|
||||
searchResults = []
|
||||
isSearching = false
|
||||
return
|
||||
}
|
||||
|
||||
guard query.count >= 2 else {
|
||||
return
|
||||
}
|
||||
|
||||
isSearching = true
|
||||
searchTask = Task {
|
||||
// Debounce
|
||||
try? await Task.sleep(for: .milliseconds(300))
|
||||
guard !Task.isCancelled else { return }
|
||||
|
||||
do {
|
||||
let results = try await repo.searchFoods(query: query)
|
||||
guard !Task.isCancelled else { return }
|
||||
searchResults = results
|
||||
} catch {
|
||||
guard !Task.isCancelled else { return }
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
isSearching = false
|
||||
}
|
||||
}
|
||||
|
||||
func selectFood(_ food: FoodItem) {
|
||||
selectedFood = food
|
||||
addQuantity = 1
|
||||
addMealType = .guess()
|
||||
showAddSheet = true
|
||||
}
|
||||
|
||||
func addFood(date: String, onComplete: @escaping () -> Void) async {
|
||||
guard let food = selectedFood else { return }
|
||||
isAddingFood = true
|
||||
|
||||
let request = CreateEntryRequest(
|
||||
foodId: food.id,
|
||||
quantity: addQuantity,
|
||||
unit: food.baseUnit ?? "serving",
|
||||
mealType: addMealType.rawValue,
|
||||
entryDate: date,
|
||||
entryMethod: "manual",
|
||||
source: "ios_app"
|
||||
)
|
||||
|
||||
do {
|
||||
_ = try await repo.createEntry(request)
|
||||
showAddSheet = false
|
||||
selectedFood = nil
|
||||
onComplete()
|
||||
} catch {
|
||||
errorMessage = "Failed to add food: \(error.localizedDescription)"
|
||||
}
|
||||
isAddingFood = false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor @Observable
|
||||
final class GoalsViewModel {
|
||||
var goal: DailyGoal = .defaultGoal
|
||||
var isLoading = true
|
||||
var errorMessage: String?
|
||||
|
||||
private let repo = FitnessRepository.shared
|
||||
|
||||
func load() async {
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
|
||||
do {
|
||||
goal = try await repo.goals(for: Date().apiDateString, forceRefresh: true)
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
|
||||
isLoading = false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor @Observable
|
||||
final class HistoryViewModel {
|
||||
var days: [HistoryDay] = []
|
||||
var isLoading = true
|
||||
var errorMessage: String?
|
||||
|
||||
private let repo = FitnessRepository.shared
|
||||
private let numberOfDays = 14
|
||||
|
||||
struct HistoryDay: Identifiable {
|
||||
let date: Date
|
||||
let dateString: String
|
||||
let entries: [FoodEntry]
|
||||
let goal: DailyGoal
|
||||
|
||||
var id: String { dateString }
|
||||
|
||||
var totalCalories: Double {
|
||||
entries.reduce(0) { $0 + $1.calories }
|
||||
}
|
||||
|
||||
var totalProtein: Double {
|
||||
entries.reduce(0) { $0 + $1.protein }
|
||||
}
|
||||
|
||||
var totalCarbs: Double {
|
||||
entries.reduce(0) { $0 + $1.carbs }
|
||||
}
|
||||
|
||||
var totalFat: Double {
|
||||
entries.reduce(0) { $0 + $1.fat }
|
||||
}
|
||||
|
||||
var entryCount: Int {
|
||||
entries.count
|
||||
}
|
||||
|
||||
var calorieProgress: Double {
|
||||
guard goal.calories > 0 else { return 0 }
|
||||
return min(totalCalories / goal.calories, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
func load() async {
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
|
||||
var results: [HistoryDay] = []
|
||||
|
||||
do {
|
||||
// Load past N days
|
||||
for i in 0..<numberOfDays {
|
||||
let date = Date().adding(days: -i)
|
||||
let dateString = date.apiDateString
|
||||
|
||||
let entries = try await repo.entries(for: dateString, forceRefresh: i == 0)
|
||||
let goal = try await repo.goals(for: dateString)
|
||||
|
||||
results.append(HistoryDay(
|
||||
date: date,
|
||||
dateString: dateString,
|
||||
entries: entries,
|
||||
goal: goal
|
||||
))
|
||||
}
|
||||
days = results
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
days = results // Show what we have
|
||||
}
|
||||
|
||||
isLoading = false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor @Observable
|
||||
final class TemplatesViewModel {
|
||||
var templates: [MealTemplate] = []
|
||||
var isLoading = true
|
||||
var errorMessage: String?
|
||||
var isLogging = false
|
||||
var loggedTemplateId: String?
|
||||
|
||||
private let repo = FitnessRepository.shared
|
||||
|
||||
func load() async {
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
|
||||
do {
|
||||
templates = try await repo.templates(forceRefresh: true)
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
func logTemplate(_ template: MealTemplate, date: String, onComplete: @escaping () -> Void) async {
|
||||
isLogging = true
|
||||
loggedTemplateId = template.id
|
||||
|
||||
do {
|
||||
try await repo.logTemplate(id: template.id, date: date)
|
||||
loggedTemplateId = nil
|
||||
onComplete()
|
||||
} catch {
|
||||
errorMessage = "Failed to log template: \(error.localizedDescription)"
|
||||
loggedTemplateId = nil
|
||||
}
|
||||
|
||||
isLogging = false
|
||||
}
|
||||
|
||||
var groupedTemplates: [String: [MealTemplate]] {
|
||||
Dictionary(grouping: templates, by: \.mealType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor @Observable
|
||||
final class TodayViewModel {
|
||||
var entries: [FoodEntry] = []
|
||||
var goal: DailyGoal = .defaultGoal
|
||||
var selectedDate: Date = Date()
|
||||
var isLoading = true
|
||||
var errorMessage: String?
|
||||
var expandedMeals: Set<String> = Set(MealType.allCases.map(\.rawValue))
|
||||
|
||||
private let repo = FitnessRepository.shared
|
||||
|
||||
// MARK: - Computed Properties
|
||||
|
||||
var dateString: String {
|
||||
selectedDate.apiDateString
|
||||
}
|
||||
|
||||
var mealGroups: [MealGroup] {
|
||||
MealType.allCases.map { meal in
|
||||
MealGroup(
|
||||
meal: meal,
|
||||
entries: entries.filter { $0.mealType == meal.rawValue }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var totalCalories: Double {
|
||||
entries.reduce(0) { $0 + $1.calories }
|
||||
}
|
||||
|
||||
var totalProtein: Double {
|
||||
entries.reduce(0) { $0 + $1.protein }
|
||||
}
|
||||
|
||||
var totalCarbs: Double {
|
||||
entries.reduce(0) { $0 + $1.carbs }
|
||||
}
|
||||
|
||||
var totalFat: Double {
|
||||
entries.reduce(0) { $0 + $1.fat }
|
||||
}
|
||||
|
||||
var caloriesRemaining: Double {
|
||||
max(goal.calories - totalCalories, 0)
|
||||
}
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
func load() async {
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
|
||||
do {
|
||||
async let entriesTask = repo.entries(for: dateString, forceRefresh: true)
|
||||
async let goalsTask = repo.goals(for: dateString)
|
||||
|
||||
entries = try await entriesTask
|
||||
goal = try await goalsTask
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
func goToNextDay() {
|
||||
selectedDate = selectedDate.adding(days: 1)
|
||||
Task { await load() }
|
||||
}
|
||||
|
||||
func goToPreviousDay() {
|
||||
selectedDate = selectedDate.adding(days: -1)
|
||||
Task { await load() }
|
||||
}
|
||||
|
||||
func goToToday() {
|
||||
selectedDate = Date()
|
||||
Task { await load() }
|
||||
}
|
||||
|
||||
func toggleMeal(_ meal: String) {
|
||||
if expandedMeals.contains(meal) {
|
||||
expandedMeals.remove(meal)
|
||||
} else {
|
||||
expandedMeals.insert(meal)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteEntry(_ entry: FoodEntry) async {
|
||||
// Optimistic removal
|
||||
entries.removeAll { $0.id == entry.id }
|
||||
do {
|
||||
try await repo.deleteEntry(id: entry.id, date: dateString)
|
||||
} catch {
|
||||
// Reload on failure
|
||||
await load()
|
||||
}
|
||||
}
|
||||
|
||||
func updateEntryQuantity(id: String, quantity: Double) async {
|
||||
let request = UpdateEntryRequest(quantity: quantity)
|
||||
do {
|
||||
_ = try await repo.updateEntry(id: id, request: request, date: dateString)
|
||||
await load()
|
||||
} catch {
|
||||
errorMessage = "Failed to update entry"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import SwiftUI
|
||||
|
||||
struct AddFoodSheet: View {
|
||||
let food: FoodItem
|
||||
@Binding var quantity: Double
|
||||
@Binding var mealType: MealType
|
||||
let isAdding: Bool
|
||||
let onAdd: () -> Void
|
||||
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var quantityText: String = "1"
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
VStack(spacing: 24) {
|
||||
// Food info header
|
||||
foodHeader
|
||||
|
||||
// Quantity input
|
||||
quantitySection
|
||||
|
||||
// Meal picker
|
||||
mealPickerSection
|
||||
|
||||
// Macro preview
|
||||
macroPreview
|
||||
|
||||
Spacer()
|
||||
|
||||
// Add button
|
||||
Button(action: onAdd) {
|
||||
HStack(spacing: 8) {
|
||||
if isAdding {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
.tint(.white)
|
||||
}
|
||||
Text("Add to \(mealType.displayName)")
|
||||
.font(.body.weight(.semibold))
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 16)
|
||||
.background(Color.accentWarm)
|
||||
.foregroundStyle(.white)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
}
|
||||
.disabled(isAdding || quantity <= 0)
|
||||
}
|
||||
.padding(20)
|
||||
.background(Color.canvas)
|
||||
.navigationTitle("Add Food")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .topBarLeading) {
|
||||
Button("Cancel") {
|
||||
dismiss()
|
||||
}
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
}
|
||||
.onAppear {
|
||||
quantityText = formatQuantity(quantity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var foodHeader: some View {
|
||||
HStack(spacing: 14) {
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(Color.accentWarmBg)
|
||||
.frame(width: 48, height: 48)
|
||||
|
||||
Image(systemName: "fork.knife")
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(food.name)
|
||||
.font(.headline)
|
||||
.foregroundStyle(Color.text1)
|
||||
.lineLimit(2)
|
||||
|
||||
Text("\(Int(food.caloriesPerBase)) kcal per \(food.displayUnit)")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
private var quantitySection: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Quantity (\(food.displayUnit))")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
.textCase(.uppercase)
|
||||
|
||||
HStack(spacing: 12) {
|
||||
// Decrement
|
||||
Button {
|
||||
adjustQuantity(by: -0.5)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle.fill")
|
||||
.font(.title2)
|
||||
.foregroundStyle(quantity > 0.5 ? Color.accentWarm : Color.text4)
|
||||
}
|
||||
.disabled(quantity <= 0.5)
|
||||
|
||||
// Text field
|
||||
TextField("1", text: $quantityText)
|
||||
.textFieldStyle(.plain)
|
||||
.keyboardType(.decimalPad)
|
||||
.multilineTextAlignment(.center)
|
||||
.font(.title2.weight(.bold))
|
||||
.foregroundStyle(Color.text1)
|
||||
.frame(width: 80)
|
||||
.padding(.vertical, 8)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 10))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 10)
|
||||
.stroke(Color.black.opacity(0.06), lineWidth: 1)
|
||||
)
|
||||
.onChange(of: quantityText) {
|
||||
if let val = Double(quantityText), val > 0 {
|
||||
quantity = val
|
||||
}
|
||||
}
|
||||
|
||||
// Increment
|
||||
Button {
|
||||
adjustQuantity(by: 0.5)
|
||||
} label: {
|
||||
Image(systemName: "plus.circle.fill")
|
||||
.font(.title2)
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
// Quick presets
|
||||
ForEach([0.5, 1.0, 2.0], id: \.self) { preset in
|
||||
Button {
|
||||
quantity = preset
|
||||
quantityText = formatQuantity(preset)
|
||||
} label: {
|
||||
Text(formatQuantity(preset))
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(quantity == preset ? .white : Color.text2)
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 6)
|
||||
.background(quantity == preset ? Color.accentWarm : Color.surfaceSecondary)
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var mealPickerSection: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Meal")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
.textCase(.uppercase)
|
||||
|
||||
HStack(spacing: 8) {
|
||||
ForEach(MealType.allCases) { meal in
|
||||
Button {
|
||||
mealType = meal
|
||||
} label: {
|
||||
VStack(spacing: 4) {
|
||||
Image(systemName: meal.icon)
|
||||
.font(.body)
|
||||
Text(meal.displayName)
|
||||
.font(.caption2.weight(.medium))
|
||||
}
|
||||
.foregroundStyle(mealType == meal ? .white : Color.text2)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 10)
|
||||
.background(
|
||||
mealType == meal
|
||||
? Color.mealColor(for: meal.rawValue)
|
||||
: Color.surfaceSecondary
|
||||
)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 10))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var macroPreview: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Text("Nutrition Preview")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
.textCase(.uppercase)
|
||||
|
||||
HStack(spacing: 0) {
|
||||
macroPreviewItem("Calories", value: food.scaledCalories(quantity: quantity), unit: "kcal", color: .caloriesColor)
|
||||
Spacer()
|
||||
macroPreviewItem("Protein", value: food.scaledProtein(quantity: quantity), unit: "g", color: .proteinColor)
|
||||
Spacer()
|
||||
macroPreviewItem("Carbs", value: food.scaledCarbs(quantity: quantity), unit: "g", color: .carbsColor)
|
||||
Spacer()
|
||||
macroPreviewItem("Fat", value: food.scaledFat(quantity: quantity), unit: "g", color: .fatColor)
|
||||
}
|
||||
.padding(16)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 12))
|
||||
}
|
||||
}
|
||||
|
||||
private func macroPreviewItem(_ label: String, value: Double, unit: String, color: Color) -> some View {
|
||||
VStack(spacing: 4) {
|
||||
Text("\(Int(value))")
|
||||
.font(.system(.title3, design: .rounded, weight: .bold))
|
||||
.foregroundStyle(color)
|
||||
Text(label)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
}
|
||||
|
||||
private func adjustQuantity(by amount: Double) {
|
||||
quantity = max(0.5, quantity + amount)
|
||||
quantityText = formatQuantity(quantity)
|
||||
}
|
||||
|
||||
private func formatQuantity(_ qty: Double) -> String {
|
||||
if qty == qty.rounded() {
|
||||
return "\(Int(qty))"
|
||||
}
|
||||
return String(format: "%.1f", qty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import SwiftUI
|
||||
|
||||
struct EntryDetailView: View {
|
||||
let entry: FoodEntry
|
||||
let onDelete: () -> Void
|
||||
let onUpdateQuantity: (Double) -> Void
|
||||
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var editQuantity: String
|
||||
@State private var showDeleteConfirm = false
|
||||
|
||||
init(entry: FoodEntry, onDelete: @escaping () -> Void, onUpdateQuantity: @escaping (Double) -> Void) {
|
||||
self.entry = entry
|
||||
self.onDelete = onDelete
|
||||
self.onUpdateQuantity = onUpdateQuantity
|
||||
_editQuantity = State(initialValue: entry.quantity == entry.quantity.rounded() ? "\(Int(entry.quantity))" : String(format: "%.1f", entry.quantity))
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
ScrollView {
|
||||
VStack(spacing: 20) {
|
||||
// Header
|
||||
entryHeader
|
||||
|
||||
// Quantity editor
|
||||
quantityEditor
|
||||
|
||||
// Macros grid
|
||||
macrosGrid
|
||||
|
||||
// Details
|
||||
detailsSection
|
||||
|
||||
// Delete button
|
||||
Button(role: .destructive) {
|
||||
showDeleteConfirm = true
|
||||
} label: {
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: "trash")
|
||||
Text("Delete Entry")
|
||||
}
|
||||
.font(.body.weight(.medium))
|
||||
.foregroundStyle(Color.error)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 14)
|
||||
.background(Color.error.opacity(0.06))
|
||||
.clipShape(RoundedRectangle(cornerRadius: 12))
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
}
|
||||
.background(Color.canvas)
|
||||
.navigationTitle("Entry Details")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .topBarTrailing) {
|
||||
Button("Done") {
|
||||
dismiss()
|
||||
}
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
}
|
||||
.confirmationDialog("Delete Entry", isPresented: $showDeleteConfirm) {
|
||||
Button("Delete", role: .destructive) {
|
||||
onDelete()
|
||||
dismiss()
|
||||
}
|
||||
Button("Cancel", role: .cancel) {}
|
||||
} message: {
|
||||
Text("Are you sure you want to delete \"\(entry.foodName)\"?")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var entryHeader: some View {
|
||||
VStack(spacing: 12) {
|
||||
ZStack {
|
||||
Circle()
|
||||
.fill(Color.mealColor(for: entry.mealType).opacity(0.1))
|
||||
.frame(width: 64, height: 64)
|
||||
|
||||
Image(systemName: Color.mealIcon(for: entry.mealType))
|
||||
.font(.title2)
|
||||
.foregroundStyle(Color.mealColor(for: entry.mealType))
|
||||
}
|
||||
|
||||
Text(entry.foodName)
|
||||
.font(.title3.weight(.semibold))
|
||||
.foregroundStyle(Color.text1)
|
||||
.multilineTextAlignment(.center)
|
||||
|
||||
Text(entry.mealType.capitalized)
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.mealColor(for: entry.mealType))
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 4)
|
||||
.background(Color.mealColor(for: entry.mealType).opacity(0.1))
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
}
|
||||
|
||||
private var quantityEditor: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Quantity")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
.textCase(.uppercase)
|
||||
|
||||
HStack(spacing: 12) {
|
||||
Button {
|
||||
let current = Double(editQuantity) ?? 1
|
||||
let newVal = max(0.5, current - 0.5)
|
||||
editQuantity = formatQuantity(newVal)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle.fill")
|
||||
.font(.title2)
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
|
||||
TextField("1", text: $editQuantity)
|
||||
.textFieldStyle(.plain)
|
||||
.keyboardType(.decimalPad)
|
||||
.multilineTextAlignment(.center)
|
||||
.font(.title2.weight(.bold))
|
||||
.foregroundStyle(Color.text1)
|
||||
.frame(width: 80)
|
||||
.padding(.vertical, 8)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 10))
|
||||
|
||||
Button {
|
||||
let current = Double(editQuantity) ?? 1
|
||||
editQuantity = formatQuantity(current + 0.5)
|
||||
} label: {
|
||||
Image(systemName: "plus.circle.fill")
|
||||
.font(.title2)
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button("Save") {
|
||||
if let qty = Double(editQuantity), qty > 0 {
|
||||
onUpdateQuantity(qty)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundStyle(.white)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
.background(Color.accentWarm)
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
}
|
||||
|
||||
private var macrosGrid: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Nutrition")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
.textCase(.uppercase)
|
||||
|
||||
LazyVGrid(columns: [
|
||||
GridItem(.flexible()),
|
||||
GridItem(.flexible()),
|
||||
GridItem(.flexible())
|
||||
], spacing: 12) {
|
||||
macroCell("Calories", value: entry.calories, unit: "kcal", color: .caloriesColor)
|
||||
macroCell("Protein", value: entry.protein, unit: "g", color: .proteinColor)
|
||||
macroCell("Carbs", value: entry.carbs, unit: "g", color: .carbsColor)
|
||||
macroCell("Fat", value: entry.fat, unit: "g", color: .fatColor)
|
||||
if let sugar = entry.sugar {
|
||||
macroCell("Sugar", value: sugar, unit: "g", color: .sugarColor)
|
||||
}
|
||||
if let fiber = entry.fiber {
|
||||
macroCell("Fiber", value: fiber, unit: "g", color: .fiberColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
}
|
||||
|
||||
private func macroCell(_ label: String, value: Double, unit: String, color: Color) -> some View {
|
||||
VStack(spacing: 4) {
|
||||
Text("\(Int(value))")
|
||||
.font(.title3.weight(.bold))
|
||||
.foregroundStyle(color)
|
||||
Text(label)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 10)
|
||||
.background(color.opacity(0.06))
|
||||
.clipShape(RoundedRectangle(cornerRadius: 10))
|
||||
}
|
||||
|
||||
private var detailsSection: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Details")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
.textCase(.uppercase)
|
||||
|
||||
VStack(spacing: 0) {
|
||||
detailRow("Serving", value: entry.servingDescription ?? "\(formatQuantity(entry.quantity)) \(entry.unit)")
|
||||
|
||||
if let method = entry.method, !method.isEmpty {
|
||||
Divider()
|
||||
detailRow("Method", value: method)
|
||||
}
|
||||
|
||||
if let note = entry.note, !note.isEmpty {
|
||||
Divider()
|
||||
detailRow("Note", value: note)
|
||||
}
|
||||
|
||||
if let loggedAt = entry.loggedAt, !loggedAt.isEmpty {
|
||||
Divider()
|
||||
detailRow("Logged", value: loggedAt)
|
||||
}
|
||||
}
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
}
|
||||
}
|
||||
|
||||
private func detailRow(_ label: String, value: String) -> some View {
|
||||
HStack {
|
||||
Text(label)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.text3)
|
||||
Spacer()
|
||||
Text(value)
|
||||
.font(.subheadline.weight(.medium))
|
||||
.foregroundStyle(Color.text1)
|
||||
.lineLimit(2)
|
||||
.multilineTextAlignment(.trailing)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 12)
|
||||
}
|
||||
|
||||
private func formatQuantity(_ qty: Double) -> String {
|
||||
if qty == qty.rounded() {
|
||||
return "\(Int(qty))"
|
||||
}
|
||||
return String(format: "%.1f", qty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import SwiftUI
|
||||
|
||||
struct FitnessTabView: View {
|
||||
@State private var selectedTab: FitnessTab = .today
|
||||
@State private var todayVM = TodayViewModel()
|
||||
@State private var showFoodSearch = false
|
||||
|
||||
enum FitnessTab: String, CaseIterable {
|
||||
case today = "Today"
|
||||
case history = "History"
|
||||
case templates = "Templates"
|
||||
case goals = "Goals"
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
VStack(spacing: 0) {
|
||||
// Custom segmented control
|
||||
tabBar
|
||||
|
||||
// Content
|
||||
Group {
|
||||
switch selectedTab {
|
||||
case .today:
|
||||
TodayView(viewModel: todayVM, showFoodSearch: $showFoodSearch)
|
||||
case .history:
|
||||
HistoryView()
|
||||
case .templates:
|
||||
TemplatesView(dateString: todayVM.dateString) {
|
||||
Task { await todayVM.load() }
|
||||
}
|
||||
case .goals:
|
||||
GoalsView()
|
||||
}
|
||||
}
|
||||
}
|
||||
.background(Color.canvas)
|
||||
.navigationTitle("Fitness")
|
||||
.navigationBarTitleDisplayMode(.large)
|
||||
.sheet(isPresented: $showFoodSearch) {
|
||||
FoodSearchView(date: todayVM.dateString) {
|
||||
Task { await todayVM.load() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var tabBar: some View {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: 6) {
|
||||
ForEach(FitnessTab.allCases, id: \.rawValue) { tab in
|
||||
Button {
|
||||
withAnimation(.easeInOut(duration: 0.2)) {
|
||||
selectedTab = tab
|
||||
}
|
||||
} label: {
|
||||
Text(tab.rawValue)
|
||||
.font(.subheadline.weight(selectedTab == tab ? .semibold : .medium))
|
||||
.foregroundStyle(selectedTab == tab ? Color.surface : Color.text3)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
.background(
|
||||
selectedTab == tab
|
||||
? Color.accentWarm
|
||||
: Color.surfaceSecondary
|
||||
)
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import SwiftUI
|
||||
|
||||
struct FoodSearchView: View {
|
||||
let date: String
|
||||
let onFoodAdded: () -> Void
|
||||
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var viewModel = FoodSearchViewModel()
|
||||
@FocusState private var searchFocused: Bool
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
VStack(spacing: 0) {
|
||||
// Search bar
|
||||
searchBar
|
||||
|
||||
// Content
|
||||
if viewModel.isSearching || viewModel.isLoadingRecent {
|
||||
LoadingView(message: viewModel.isSearching ? "Searching..." : "Loading recent...")
|
||||
} else if viewModel.displayedFoods.isEmpty && !viewModel.isShowingRecent {
|
||||
EmptyStateView(
|
||||
icon: "magnifyingglass",
|
||||
title: "No results",
|
||||
subtitle: "Try a different search term"
|
||||
)
|
||||
} else {
|
||||
foodList
|
||||
}
|
||||
}
|
||||
.background(Color.canvas)
|
||||
.navigationTitle("Add Food")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .topBarLeading) {
|
||||
Button("Cancel") {
|
||||
dismiss()
|
||||
}
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $viewModel.showAddSheet) {
|
||||
if let food = viewModel.selectedFood {
|
||||
AddFoodSheet(
|
||||
food: food,
|
||||
quantity: $viewModel.addQuantity,
|
||||
mealType: $viewModel.addMealType,
|
||||
isAdding: viewModel.isAddingFood
|
||||
) {
|
||||
Task {
|
||||
await viewModel.addFood(date: date) {
|
||||
onFoodAdded()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
.presentationDetents([.medium])
|
||||
}
|
||||
}
|
||||
.task {
|
||||
await viewModel.loadRecent()
|
||||
searchFocused = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var searchBar: some View {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: "magnifyingglass")
|
||||
.foregroundStyle(Color.text4)
|
||||
|
||||
TextField("Search foods...", text: $viewModel.searchText)
|
||||
.textFieldStyle(.plain)
|
||||
.autocorrectionDisabled()
|
||||
.textInputAutocapitalization(.never)
|
||||
.focused($searchFocused)
|
||||
.onSubmit {
|
||||
viewModel.search()
|
||||
}
|
||||
.onChange(of: viewModel.searchText) {
|
||||
viewModel.search()
|
||||
}
|
||||
|
||||
if !viewModel.searchText.isEmpty {
|
||||
Button {
|
||||
viewModel.searchText = ""
|
||||
viewModel.searchResults = []
|
||||
} label: {
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 12))
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
private var foodList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 0) {
|
||||
if viewModel.isShowingRecent && !viewModel.recentFoods.isEmpty {
|
||||
sectionHeader("Recent Foods")
|
||||
}
|
||||
|
||||
ForEach(viewModel.displayedFoods) { food in
|
||||
FoodItemRow(food: food) {
|
||||
viewModel.selectFood(food)
|
||||
}
|
||||
Divider()
|
||||
.padding(.leading, 60)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func sectionHeader(_ title: String) -> some View {
|
||||
Text(title)
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text4)
|
||||
.textCase(.uppercase)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.top, 16)
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
}
|
||||
|
||||
struct FoodItemRow: View {
|
||||
let food: FoodItem
|
||||
let onTap: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Button(action: onTap) {
|
||||
HStack(spacing: 12) {
|
||||
// Icon
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 10)
|
||||
.fill(Color.accentWarmBg)
|
||||
.frame(width: 40, height: 40)
|
||||
|
||||
if let imageUrl = food.imageUrl, !imageUrl.isEmpty {
|
||||
AsyncImage(url: URL(string: imageUrl)) { image in
|
||||
image
|
||||
.resizable()
|
||||
.scaledToFill()
|
||||
.frame(width: 40, height: 40)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 10))
|
||||
} placeholder: {
|
||||
Image(systemName: "fork.knife")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
} else {
|
||||
Image(systemName: "fork.knife")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
}
|
||||
|
||||
// Info
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(food.name)
|
||||
.font(.subheadline.weight(.medium))
|
||||
.foregroundStyle(Color.text1)
|
||||
.lineLimit(1)
|
||||
|
||||
Text(food.displayInfo)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
.lineLimit(1)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
// Calories
|
||||
VStack(alignment: .trailing, spacing: 2) {
|
||||
Text("\(Int(food.caloriesPerBase))")
|
||||
.font(.subheadline.weight(.bold))
|
||||
.foregroundStyle(Color.text1)
|
||||
|
||||
Text("kcal")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
|
||||
Image(systemName: "chevron.right")
|
||||
.font(.caption2.weight(.semibold))
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 10)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import SwiftUI
|
||||
|
||||
struct GoalsView: View {
|
||||
@State private var viewModel = GoalsViewModel()
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
if viewModel.isLoading {
|
||||
LoadingView(message: "Loading goals...")
|
||||
.frame(height: 300)
|
||||
} else {
|
||||
VStack(spacing: 20) {
|
||||
// Header
|
||||
Text("Your daily targets")
|
||||
.font(.headline)
|
||||
.foregroundStyle(Color.text1)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
|
||||
// Goals cards
|
||||
goalCard(
|
||||
label: "Calories",
|
||||
value: viewModel.goal.calories,
|
||||
unit: "kcal",
|
||||
icon: "flame.fill",
|
||||
color: .caloriesColor
|
||||
)
|
||||
|
||||
goalCard(
|
||||
label: "Protein",
|
||||
value: viewModel.goal.protein,
|
||||
unit: "g",
|
||||
icon: "circle.hexagonpath.fill",
|
||||
color: .proteinColor
|
||||
)
|
||||
|
||||
goalCard(
|
||||
label: "Carbs",
|
||||
value: viewModel.goal.carbs,
|
||||
unit: "g",
|
||||
icon: "bolt.fill",
|
||||
color: .carbsColor
|
||||
)
|
||||
|
||||
goalCard(
|
||||
label: "Fat",
|
||||
value: viewModel.goal.fat,
|
||||
unit: "g",
|
||||
icon: "drop.fill",
|
||||
color: .fatColor
|
||||
)
|
||||
|
||||
if let sugar = viewModel.goal.sugar, sugar > 0 {
|
||||
goalCard(
|
||||
label: "Sugar",
|
||||
value: sugar,
|
||||
unit: "g",
|
||||
icon: "cube.fill",
|
||||
color: .sugarColor
|
||||
)
|
||||
}
|
||||
|
||||
if let fiber = viewModel.goal.fiber, fiber > 0 {
|
||||
goalCard(
|
||||
label: "Fiber",
|
||||
value: fiber,
|
||||
unit: "g",
|
||||
icon: "leaf.fill",
|
||||
color: .fiberColor
|
||||
)
|
||||
}
|
||||
|
||||
// Info note
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: "info.circle")
|
||||
.foregroundStyle(Color.text4)
|
||||
Text("Goals can be updated from the web app")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.top, 8)
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
|
||||
if let error = viewModel.errorMessage {
|
||||
ErrorBanner(message: error) {
|
||||
Task { await viewModel.load() }
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
}
|
||||
.refreshable {
|
||||
await viewModel.load()
|
||||
}
|
||||
.task {
|
||||
await viewModel.load()
|
||||
}
|
||||
}
|
||||
|
||||
private func goalCard(label: String, value: Double, unit: String, icon: String, color: Color) -> some View {
|
||||
HStack(spacing: 16) {
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(color.opacity(0.1))
|
||||
.frame(width: 48, height: 48)
|
||||
|
||||
Image(systemName: icon)
|
||||
.font(.title3)
|
||||
.foregroundStyle(color)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(label)
|
||||
.font(.subheadline.weight(.medium))
|
||||
.foregroundStyle(Color.text2)
|
||||
|
||||
Text("Daily target")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
HStack(alignment: .firstTextBaseline, spacing: 2) {
|
||||
Text("\(Int(value))")
|
||||
.font(.title2.weight(.bold))
|
||||
.foregroundStyle(Color.text1)
|
||||
Text(unit)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
.shadow(color: .black.opacity(0.03), radius: 4, y: 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import SwiftUI
|
||||
|
||||
struct HistoryView: View {
|
||||
@State private var viewModel = HistoryViewModel()
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
if viewModel.isLoading {
|
||||
LoadingView(message: "Loading history...")
|
||||
.frame(height: 300)
|
||||
} else if viewModel.days.isEmpty {
|
||||
EmptyStateView(
|
||||
icon: "calendar",
|
||||
title: "No history",
|
||||
subtitle: "Start logging food to see your history"
|
||||
)
|
||||
} else {
|
||||
LazyVStack(spacing: 12) {
|
||||
ForEach(viewModel.days) { day in
|
||||
HistoryDayCard(day: day)
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
|
||||
if let error = viewModel.errorMessage {
|
||||
ErrorBanner(message: error) {
|
||||
Task { await viewModel.load() }
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
}
|
||||
.refreshable {
|
||||
await viewModel.load()
|
||||
}
|
||||
.task {
|
||||
await viewModel.load()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct HistoryDayCard: View {
|
||||
let day: HistoryViewModel.HistoryDay
|
||||
@State private var isExpanded = false
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
// Header
|
||||
Button {
|
||||
withAnimation(.easeInOut(duration: 0.2)) {
|
||||
isExpanded.toggle()
|
||||
}
|
||||
} label: {
|
||||
HStack(spacing: 12) {
|
||||
// Date
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(day.date.relativeLabel)
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundStyle(Color.text1)
|
||||
Text(day.date.shortDisplayString)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
// Quick stats
|
||||
HStack(spacing: 16) {
|
||||
VStack(spacing: 2) {
|
||||
Text("\(Int(day.totalCalories))")
|
||||
.font(.subheadline.weight(.bold))
|
||||
.foregroundStyle(Color.text1)
|
||||
Text("kcal")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
|
||||
// Mini progress ring
|
||||
ZStack {
|
||||
Circle()
|
||||
.stroke(Color.caloriesColor.opacity(0.12), lineWidth: 3)
|
||||
Circle()
|
||||
.trim(from: 0, to: day.calorieProgress)
|
||||
.stroke(Color.caloriesColor, style: StrokeStyle(lineWidth: 3, lineCap: .round))
|
||||
.rotationEffect(.degrees(-90))
|
||||
}
|
||||
.frame(width: 28, height: 28)
|
||||
}
|
||||
|
||||
Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
|
||||
if isExpanded {
|
||||
Divider()
|
||||
.padding(.horizontal, 16)
|
||||
|
||||
// Macros row
|
||||
HStack(spacing: 0) {
|
||||
historyMacro("Protein", value: day.totalProtein, color: .proteinColor)
|
||||
Spacer()
|
||||
historyMacro("Carbs", value: day.totalCarbs, color: .carbsColor)
|
||||
Spacer()
|
||||
historyMacro("Fat", value: day.totalFat, color: .fatColor)
|
||||
Spacer()
|
||||
historyMacro("Entries", value: Double(day.entryCount), color: .text3, isCount: true)
|
||||
}
|
||||
.padding(.horizontal, 20)
|
||||
.padding(.vertical, 12)
|
||||
|
||||
if !day.entries.isEmpty {
|
||||
Divider()
|
||||
.padding(.horizontal, 16)
|
||||
|
||||
// Entries list
|
||||
ForEach(day.entries) { entry in
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(Color.mealColor(for: entry.mealType))
|
||||
.frame(width: 6, height: 6)
|
||||
|
||||
Text(entry.foodName)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text2)
|
||||
.lineLimit(1)
|
||||
|
||||
Spacer()
|
||||
|
||||
Text("\(Int(entry.calories)) kcal")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
.padding(.horizontal, 20)
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
.shadow(color: .black.opacity(0.03), radius: 4, y: 2)
|
||||
}
|
||||
|
||||
private func historyMacro(_ label: String, value: Double, color: Color, isCount: Bool = false) -> some View {
|
||||
VStack(spacing: 2) {
|
||||
Text("\(Int(value))\(isCount ? "" : "g")")
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundStyle(color)
|
||||
Text(label)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import SwiftUI
|
||||
|
||||
struct MealSectionView: View {
|
||||
let group: MealGroup
|
||||
let isExpanded: Bool
|
||||
let onToggle: () -> Void
|
||||
let onDelete: (FoodEntry) -> Void
|
||||
let onAddFood: () -> Void
|
||||
|
||||
@State private var selectedEntry: FoodEntry?
|
||||
|
||||
private var mealColor: Color {
|
||||
Color.mealColor(for: group.meal.rawValue)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
// Header
|
||||
Button(action: onToggle) {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: group.meal.icon)
|
||||
.font(.body)
|
||||
.foregroundStyle(mealColor)
|
||||
.frame(width: 28)
|
||||
|
||||
Text(group.meal.displayName)
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundStyle(Color.text1)
|
||||
|
||||
if !group.entries.isEmpty {
|
||||
Text("\(group.entries.count)")
|
||||
.font(.caption2.weight(.bold))
|
||||
.foregroundStyle(mealColor)
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 2)
|
||||
.background(mealColor.opacity(0.1))
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
if !group.entries.isEmpty {
|
||||
Text("\(Int(group.totalCalories)) kcal")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
|
||||
Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 14)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
|
||||
// Entries
|
||||
if isExpanded {
|
||||
if group.entries.isEmpty {
|
||||
emptyMealView
|
||||
} else {
|
||||
Divider()
|
||||
.padding(.horizontal, 16)
|
||||
|
||||
ForEach(group.entries) { entry in
|
||||
SwipeToDeleteRow(onDelete: { onDelete(entry) }) {
|
||||
EntryRow(entry: entry)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture {
|
||||
selectedEntry = entry
|
||||
}
|
||||
}
|
||||
|
||||
if entry.id != group.entries.last?.id {
|
||||
Divider()
|
||||
.padding(.leading, 52)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
.shadow(color: .black.opacity(0.03), radius: 4, y: 2)
|
||||
.sheet(item: $selectedEntry) { entry in
|
||||
EntryDetailView(
|
||||
entry: entry,
|
||||
onDelete: { onDelete(entry) },
|
||||
onUpdateQuantity: { _ in }
|
||||
)
|
||||
.presentationDetents([.large])
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyMealView: some View {
|
||||
Button(action: onAddFood) {
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: "plus.circle")
|
||||
.foregroundStyle(mealColor)
|
||||
Text("Add food")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, 16)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Swipe to Delete Row
|
||||
|
||||
struct SwipeToDeleteRow<Content: View>: View {
|
||||
let onDelete: () -> Void
|
||||
@ViewBuilder let content: () -> Content
|
||||
|
||||
@State private var offset: CGFloat = 0
|
||||
@State private var showDelete = false
|
||||
|
||||
private let deleteThreshold: CGFloat = -80
|
||||
private let deleteWidth: CGFloat = 80
|
||||
|
||||
var body: some View {
|
||||
ZStack(alignment: .trailing) {
|
||||
// Delete background
|
||||
HStack {
|
||||
Spacer()
|
||||
Button(action: {
|
||||
withAnimation(.easeOut(duration: 0.2)) {
|
||||
offset = -300
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
|
||||
onDelete()
|
||||
}
|
||||
}) {
|
||||
Image(systemName: "trash.fill")
|
||||
.foregroundStyle(.white)
|
||||
.frame(width: deleteWidth, height: .infinity)
|
||||
}
|
||||
.frame(width: deleteWidth)
|
||||
.background(Color.error)
|
||||
}
|
||||
.opacity(offset < 0 ? 1 : 0)
|
||||
|
||||
// Content
|
||||
content()
|
||||
.offset(x: offset)
|
||||
.gesture(
|
||||
DragGesture(minimumDistance: 20)
|
||||
.onChanged { value in
|
||||
let translation = value.translation.width
|
||||
if translation < 0 {
|
||||
offset = translation
|
||||
}
|
||||
}
|
||||
.onEnded { value in
|
||||
withAnimation(.easeOut(duration: 0.2)) {
|
||||
if offset < deleteThreshold {
|
||||
offset = -deleteWidth
|
||||
showDelete = true
|
||||
} else {
|
||||
offset = 0
|
||||
showDelete = false
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
.onTapGesture {
|
||||
if showDelete {
|
||||
withAnimation(.easeOut(duration: 0.2)) {
|
||||
offset = 0
|
||||
showDelete = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.clipped()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Entry Row
|
||||
|
||||
struct EntryRow: View {
|
||||
let entry: FoodEntry
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 12) {
|
||||
// Food icon or image
|
||||
ZStack {
|
||||
Circle()
|
||||
.fill(Color.mealColor(for: entry.mealType).opacity(0.1))
|
||||
.frame(width: 36, height: 36)
|
||||
|
||||
if let imageUrl = entry.imageUrl, !imageUrl.isEmpty {
|
||||
AsyncImage(url: URL(string: imageUrl)) { image in
|
||||
image
|
||||
.resizable()
|
||||
.scaledToFill()
|
||||
.frame(width: 36, height: 36)
|
||||
.clipShape(Circle())
|
||||
} placeholder: {
|
||||
Image(systemName: "fork.knife")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.mealColor(for: entry.mealType))
|
||||
}
|
||||
} else {
|
||||
Image(systemName: "fork.knife")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.mealColor(for: entry.mealType))
|
||||
}
|
||||
}
|
||||
|
||||
// Name and serving
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(entry.foodName)
|
||||
.font(.subheadline.weight(.medium))
|
||||
.foregroundStyle(Color.text1)
|
||||
.lineLimit(1)
|
||||
|
||||
Text(entry.servingDescription ?? "\(formatQuantity(entry.quantity)) \(entry.unit)")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
.lineLimit(1)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
// Macros
|
||||
VStack(alignment: .trailing, spacing: 2) {
|
||||
Text("\(Int(entry.calories))")
|
||||
.font(.subheadline.weight(.bold))
|
||||
.foregroundStyle(Color.text1)
|
||||
+ Text(" kcal")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.text3)
|
||||
|
||||
HStack(spacing: 6) {
|
||||
macroTag("P", value: entry.protein, color: .proteinColor)
|
||||
macroTag("C", value: entry.carbs, color: .carbsColor)
|
||||
macroTag("F", value: entry.fat, color: .fatColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 10)
|
||||
.background(Color.surface)
|
||||
}
|
||||
|
||||
private func macroTag(_ label: String, value: Double, color: Color) -> some View {
|
||||
Text("\(label)\(Int(value))")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
.foregroundStyle(color)
|
||||
}
|
||||
|
||||
private func formatQuantity(_ qty: Double) -> String {
|
||||
if qty == qty.rounded() {
|
||||
return "\(Int(qty))"
|
||||
}
|
||||
return String(format: "%.1f", qty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import SwiftUI
|
||||
|
||||
struct TemplatesView: View {
|
||||
let dateString: String
|
||||
let onTemplateLogged: () -> Void
|
||||
|
||||
@State private var viewModel = TemplatesViewModel()
|
||||
@State private var confirmTemplate: MealTemplate?
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
if viewModel.isLoading {
|
||||
LoadingView(message: "Loading templates...")
|
||||
.frame(height: 300)
|
||||
} else if viewModel.templates.isEmpty {
|
||||
EmptyStateView(
|
||||
icon: "doc.text",
|
||||
title: "No templates",
|
||||
subtitle: "Create templates on the web app to quickly log meals"
|
||||
)
|
||||
} else {
|
||||
LazyVStack(spacing: 16) {
|
||||
ForEach(MealType.allCases) { meal in
|
||||
let templates = viewModel.groupedTemplates[meal.rawValue] ?? []
|
||||
if !templates.isEmpty {
|
||||
templateSection(meal: meal, templates: templates)
|
||||
}
|
||||
}
|
||||
|
||||
// Ungrouped
|
||||
let ungrouped = viewModel.templates.filter { template in
|
||||
!MealType.allCases.map(\.rawValue).contains(template.mealType)
|
||||
}
|
||||
if !ungrouped.isEmpty {
|
||||
templateSection(mealLabel: "Other", icon: "ellipsis.circle.fill", color: .text3, templates: ungrouped)
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
|
||||
if let error = viewModel.errorMessage {
|
||||
ErrorBanner(message: error) {
|
||||
Task { await viewModel.load() }
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
}
|
||||
.refreshable {
|
||||
await viewModel.load()
|
||||
}
|
||||
.task {
|
||||
await viewModel.load()
|
||||
}
|
||||
.confirmationDialog(
|
||||
"Log Template",
|
||||
isPresented: Binding(
|
||||
get: { confirmTemplate != nil },
|
||||
set: { if !$0 { confirmTemplate = nil } }
|
||||
),
|
||||
presenting: confirmTemplate
|
||||
) { template in
|
||||
Button("Log \"\(template.name)\"") {
|
||||
Task {
|
||||
await viewModel.logTemplate(template, date: dateString) {
|
||||
onTemplateLogged()
|
||||
}
|
||||
}
|
||||
}
|
||||
Button("Cancel", role: .cancel) {}
|
||||
} message: { template in
|
||||
Text("This will add all items from \"\(template.name)\" (\(Int(template.calories)) kcal) to \(dateString).")
|
||||
}
|
||||
}
|
||||
|
||||
private func templateSection(meal: MealType, templates: [MealTemplate]) -> some View {
|
||||
templateSection(
|
||||
mealLabel: meal.displayName,
|
||||
icon: meal.icon,
|
||||
color: Color.mealColor(for: meal.rawValue),
|
||||
templates: templates
|
||||
)
|
||||
}
|
||||
|
||||
private func templateSection(mealLabel: String, icon: String, color: Color, templates: [MealTemplate]) -> some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: icon)
|
||||
.foregroundStyle(color)
|
||||
Text(mealLabel)
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundStyle(Color.text1)
|
||||
}
|
||||
|
||||
ForEach(templates) { template in
|
||||
TemplateCard(
|
||||
template: template,
|
||||
isLogging: viewModel.loggedTemplateId == template.id
|
||||
) {
|
||||
confirmTemplate = template
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TemplateCard: View {
|
||||
let template: MealTemplate
|
||||
let isLogging: Bool
|
||||
let onLog: () -> Void
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 14) {
|
||||
// Icon
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 10)
|
||||
.fill(Color.mealColor(for: template.mealType).opacity(0.1))
|
||||
.frame(width: 44, height: 44)
|
||||
|
||||
Image(systemName: "doc.text.fill")
|
||||
.foregroundStyle(Color.mealColor(for: template.mealType))
|
||||
}
|
||||
|
||||
// Info
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(template.name)
|
||||
.font(.subheadline.weight(.medium))
|
||||
.foregroundStyle(Color.text1)
|
||||
.lineLimit(1)
|
||||
|
||||
HStack(spacing: 8) {
|
||||
Text("\(Int(template.calories)) kcal")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.caloriesColor)
|
||||
|
||||
if let count = template.itemsCount {
|
||||
Text("\(count) items")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text4)
|
||||
}
|
||||
|
||||
if let protein = template.protein {
|
||||
Text("P\(Int(protein))")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.proteinColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
// Log button
|
||||
Button(action: onLog) {
|
||||
if isLogging {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
.tint(Color.accentWarm)
|
||||
} else {
|
||||
Image(systemName: "plus.circle.fill")
|
||||
.font(.title3)
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
}
|
||||
}
|
||||
.disabled(isLogging)
|
||||
}
|
||||
.padding(14)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
.shadow(color: .black.opacity(0.03), radius: 4, y: 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import SwiftUI
|
||||
|
||||
struct TodayView: View {
|
||||
@Bindable var viewModel: TodayViewModel
|
||||
@Binding var showFoodSearch: Bool
|
||||
|
||||
var body: some View {
|
||||
ZStack(alignment: .bottomTrailing) {
|
||||
ScrollView {
|
||||
VStack(spacing: 16) {
|
||||
// Date selector
|
||||
dateSelector
|
||||
|
||||
if viewModel.isLoading {
|
||||
LoadingView(message: "Loading entries...")
|
||||
.frame(height: 200)
|
||||
} else {
|
||||
// Macro summary card
|
||||
macroSummaryCard
|
||||
|
||||
// Meal sections
|
||||
ForEach(viewModel.mealGroups) { group in
|
||||
MealSectionView(
|
||||
group: group,
|
||||
isExpanded: viewModel.expandedMeals.contains(group.meal.rawValue),
|
||||
onToggle: { viewModel.toggleMeal(group.meal.rawValue) },
|
||||
onDelete: { entry in
|
||||
Task { await viewModel.deleteEntry(entry) }
|
||||
},
|
||||
onAddFood: {
|
||||
showFoodSearch = true
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Bottom spacing for FAB
|
||||
Spacer()
|
||||
.frame(height: 80)
|
||||
}
|
||||
|
||||
if let error = viewModel.errorMessage {
|
||||
ErrorBanner(message: error) {
|
||||
Task { await viewModel.load() }
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
.refreshable {
|
||||
await viewModel.load()
|
||||
}
|
||||
|
||||
// Floating add button
|
||||
addButton
|
||||
}
|
||||
.task {
|
||||
await viewModel.load()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Date Selector
|
||||
|
||||
private var dateSelector: some View {
|
||||
HStack(spacing: 0) {
|
||||
Button {
|
||||
viewModel.goToPreviousDay()
|
||||
} label: {
|
||||
Image(systemName: "chevron.left")
|
||||
.font(.body.weight(.semibold))
|
||||
.foregroundStyle(Color.accentWarm)
|
||||
.frame(width: 44, height: 44)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
VStack(spacing: 2) {
|
||||
Text(viewModel.selectedDate.relativeLabel)
|
||||
.font(.headline)
|
||||
.foregroundStyle(Color.text1)
|
||||
if !viewModel.selectedDate.isToday {
|
||||
Text(viewModel.selectedDate.displayString)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.text3)
|
||||
}
|
||||
}
|
||||
.onTapGesture {
|
||||
viewModel.goToToday()
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
viewModel.goToNextDay()
|
||||
} label: {
|
||||
Image(systemName: "chevron.right")
|
||||
.font(.body.weight(.semibold))
|
||||
.foregroundStyle(
|
||||
viewModel.selectedDate.isToday ? Color.text4 : Color.accentWarm
|
||||
)
|
||||
.frame(width: 44, height: 44)
|
||||
}
|
||||
.disabled(viewModel.selectedDate.isToday)
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
.padding(.vertical, 4)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14))
|
||||
.shadow(color: .black.opacity(0.03), radius: 4, y: 2)
|
||||
}
|
||||
|
||||
// MARK: - Macro Summary
|
||||
|
||||
private var macroSummaryCard: some View {
|
||||
VStack(spacing: 16) {
|
||||
// Calories ring
|
||||
HStack(spacing: 20) {
|
||||
MacroRingLarge(
|
||||
current: viewModel.totalCalories,
|
||||
goal: viewModel.goal.calories,
|
||||
color: .caloriesColor,
|
||||
size: 100,
|
||||
lineWidth: 9
|
||||
)
|
||||
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
macroRow("Protein", current: viewModel.totalProtein, goal: viewModel.goal.protein, color: .proteinColor)
|
||||
macroRow("Carbs", current: viewModel.totalCarbs, goal: viewModel.goal.carbs, color: .carbsColor)
|
||||
macroRow("Fat", current: viewModel.totalFat, goal: viewModel.goal.fat, color: .fatColor)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.background(Color.surface)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 16))
|
||||
.shadow(color: .black.opacity(0.04), radius: 8, y: 4)
|
||||
}
|
||||
|
||||
private func macroRow(_ label: String, current: Double, goal: Double, color: Color) -> some View {
|
||||
VStack(spacing: 4) {
|
||||
HStack {
|
||||
Text(label)
|
||||
.font(.caption.weight(.medium))
|
||||
.foregroundStyle(Color.text3)
|
||||
Spacer()
|
||||
Text("\(Int(current))/\(Int(goal))g")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.text2)
|
||||
}
|
||||
MacroBarCompact(current: current, goal: goal, color: color)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Add Button
|
||||
|
||||
private var addButton: some View {
|
||||
Button {
|
||||
showFoodSearch = true
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
.font(.title2.weight(.semibold))
|
||||
.foregroundStyle(.white)
|
||||
.frame(width: 56, height: 56)
|
||||
.background(Color.accentWarm)
|
||||
.clipShape(Circle())
|
||||
.shadow(color: Color.accentWarm.opacity(0.3), radius: 8, y: 4)
|
||||
}
|
||||
.padding(20)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user