AddCarbsRootView.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import CoreData
  2. import SwiftUI
  3. import Swinject
  4. extension AddCarbs {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. let editMode: Bool
  8. let override: Bool
  9. @StateObject var state = StateModel()
  10. @State var dish: String = ""
  11. @State var isPromptPresented = false
  12. @State var saved = false
  13. @State var pushed = false
  14. @State private var showAlert = false
  15. @FocusState private var isFocused: Bool
  16. @FetchRequest(
  17. entity: Presets.entity(),
  18. sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
  19. ) var carbPresets: FetchedResults<Presets>
  20. @Environment(\.managedObjectContext) var moc
  21. private var formatter: NumberFormatter {
  22. let formatter = NumberFormatter()
  23. formatter.numberStyle = .decimal
  24. formatter.maximumFractionDigits = 1
  25. return formatter
  26. }
  27. var body: some View {
  28. Form {
  29. if let carbsReq = state.carbsRequired, state.carbs < carbsReq {
  30. Section {
  31. HStack {
  32. Text("Carbs required")
  33. Spacer()
  34. Text((formatter.string(from: carbsReq as NSNumber) ?? "") + " g")
  35. }
  36. }
  37. }
  38. Section {
  39. HStack {
  40. Text("Carbs").fontWeight(.semibold)
  41. Spacer()
  42. DecimalTextField(
  43. "0",
  44. value: $state.carbs,
  45. formatter: formatter,
  46. autofocus: true,
  47. cleanInput: true
  48. )
  49. Text("grams").foregroundColor(.secondary)
  50. }
  51. if state.useFPUconversion {
  52. proteinAndFat()
  53. }
  54. // Summary when combining presets
  55. if state.waitersNotepad() != "" {
  56. HStack {
  57. Text("Total")
  58. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  59. HStack(spacing: 0) {
  60. ForEach(test, id: \.self) {
  61. Text($0).foregroundStyle(Color.randomGreen()).font(.footnote)
  62. Text($0 == test[test.count - 1] ? "" : ", ")
  63. }
  64. }.frame(maxWidth: .infinity, alignment: .trailing)
  65. }
  66. }
  67. // Time
  68. HStack {
  69. Text("Time")
  70. Spacer()
  71. if !pushed {
  72. Button {
  73. pushed = true
  74. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary).padding(.trailing, 5)
  75. } else {
  76. Button { state.date = state.date.addingTimeInterval(-10.minutes.timeInterval) }
  77. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  78. DatePicker(
  79. "Time",
  80. selection: $state.date,
  81. displayedComponents: [.hourAndMinute]
  82. ).controlSize(.mini)
  83. .labelsHidden()
  84. Button {
  85. state.date = state.date.addingTimeInterval(10.minutes.timeInterval)
  86. }
  87. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  88. }
  89. }
  90. // Optional meal note
  91. HStack {
  92. Text("Note").foregroundColor(.secondary)
  93. TextField("", text: $state.note).multilineTextAlignment(.trailing)
  94. if state.note != "", isFocused {
  95. Button { isFocused = false } label: { Image(systemName: "keyboard.chevron.compact.down") }
  96. .controlSize(.mini)
  97. }
  98. }
  99. .focused($isFocused)
  100. .popover(isPresented: $isPromptPresented) {
  101. presetPopover
  102. }
  103. }
  104. Section {
  105. Button { state.add(override, fetch: editMode) }
  106. label: { Text((state.skipBolus && !override && !editMode) ? "Save" : "Continue") }
  107. .disabled(empty)
  108. .frame(maxWidth: .infinity, alignment: .center)
  109. }.listRowBackground(!empty ? Color(.systemBlue) : Color(.systemGray4))
  110. .tint(.white)
  111. Section {
  112. mealPresets
  113. }
  114. }
  115. .onAppear {
  116. configureView {
  117. state.loadEntries(editMode)
  118. }
  119. }
  120. .navigationTitle("Add Meal")
  121. .navigationBarTitleDisplayMode(.inline)
  122. .navigationBarItems(trailing: Button("Close", action: state.hideModal))
  123. }
  124. private var presetPopover: some View {
  125. Form {
  126. Section {
  127. TextField("Name Of Dish", text: $dish)
  128. Button {
  129. saved = true
  130. if dish != "", saved {
  131. let preset = Presets(context: moc)
  132. preset.dish = dish
  133. preset.fat = state.fat as NSDecimalNumber
  134. preset.protein = state.protein as NSDecimalNumber
  135. preset.carbs = state.carbs as NSDecimalNumber
  136. try? moc.save()
  137. state.addNewPresetToWaitersNotepad(dish)
  138. saved = false
  139. isPromptPresented = false
  140. }
  141. }
  142. label: { Text("Save") }
  143. Button {
  144. dish = ""
  145. saved = false
  146. isPromptPresented = false }
  147. label: { Text("Cancel") }
  148. } header: { Text("Enter Meal Preset Name") }
  149. }
  150. }
  151. private var empty: Bool {
  152. state.carbs <= 0 && state.fat <= 0 && state.protein <= 0
  153. }
  154. private var minusButton: some View {
  155. Button {
  156. if state.carbs != 0,
  157. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  158. {
  159. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  160. } else { state.carbs = 0 }
  161. if state.fat != 0,
  162. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  163. {
  164. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  165. } else { state.fat = 0 }
  166. if state.protein != 0,
  167. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  168. {
  169. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  170. } else { state.protein = 0 }
  171. state.removePresetFromNewMeal()
  172. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  173. }
  174. label: { Image(systemName: "minus.circle") }
  175. .disabled(
  176. state
  177. .selection == nil ||
  178. (
  179. !state.summation
  180. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  181. )
  182. )
  183. .buttonStyle(.borderless)
  184. .tint(.blue)
  185. }
  186. private var plusButton: some View {
  187. Button {
  188. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  189. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  190. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  191. state.addPresetToNewMeal()
  192. }
  193. label: { Image(systemName: "plus.circle") }
  194. .disabled(state.selection == nil)
  195. .buttonStyle(.borderless)
  196. .tint(.blue)
  197. }
  198. private var mealPresets: some View {
  199. Section {
  200. HStack {
  201. if state.selection != nil {
  202. minusButton
  203. }
  204. Picker("Preset", selection: $state.selection) {
  205. Text("Saved Food").tag(nil as Presets?)
  206. ForEach(carbPresets, id: \.self) { (preset: Presets) in
  207. Text(preset.dish ?? "").tag(preset as Presets?)
  208. }
  209. }
  210. .labelsHidden()
  211. .frame(maxWidth: .infinity, alignment: .center)
  212. ._onBindingChange($state.selection) { _ in
  213. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  214. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  215. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  216. state.addToSummation()
  217. }
  218. if state.selection != nil {
  219. plusButton
  220. }
  221. }
  222. HStack {
  223. Button("Delete Preset") {
  224. showAlert.toggle()
  225. }
  226. .disabled(state.selection == nil)
  227. .tint(.orange)
  228. .buttonStyle(.borderless)
  229. .alert(
  230. "Delete preset '\(state.selection?.dish ?? "")'?",
  231. isPresented: $showAlert,
  232. actions: {
  233. Button("No", role: .cancel) {}
  234. Button("Yes", role: .destructive) {
  235. state.deletePreset()
  236. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  237. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  238. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  239. state.addPresetToNewMeal()
  240. }
  241. }
  242. )
  243. Spacer()
  244. Button {
  245. isPromptPresented = true
  246. }
  247. label: { Text("Save as Preset") }
  248. .buttonStyle(.borderless)
  249. .disabled(
  250. empty ||
  251. (
  252. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  253. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  254. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  255. .protein
  256. )
  257. )
  258. }
  259. }
  260. }
  261. @ViewBuilder private func proteinAndFat() -> some View {
  262. HStack {
  263. Text("Fat").foregroundColor(.orange)
  264. Spacer()
  265. DecimalTextField(
  266. "0",
  267. value: $state.fat,
  268. formatter: formatter,
  269. autofocus: false,
  270. cleanInput: true
  271. )
  272. Text("grams").foregroundColor(.secondary)
  273. }
  274. HStack {
  275. Text("Protein").foregroundColor(.red)
  276. Spacer()
  277. DecimalTextField(
  278. "0",
  279. value: $state.protein,
  280. formatter: formatter,
  281. autofocus: false,
  282. cleanInput: true
  283. ).foregroundColor(.loopRed)
  284. Text("grams").foregroundColor(.secondary)
  285. }
  286. }
  287. }
  288. }
  289. public extension Color {
  290. static func randomGreen(randomOpacity: Bool = false) -> Color {
  291. Color(
  292. red: .random(in: 0 ... 1),
  293. green: .random(in: 0.4 ... 0.7),
  294. blue: .random(in: 0.2 ... 1),
  295. opacity: randomOpacity ? .random(in: 0.8 ... 1) : 1
  296. )
  297. }
  298. }