AddCarbsRootView.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. let now = Date.now
  70. Text("Time")
  71. Spacer()
  72. if !pushed {
  73. Button {
  74. pushed = true
  75. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary).padding(.trailing, 5)
  76. } else {
  77. Button { state.date = state.date.addingTimeInterval(-10.minutes.timeInterval) }
  78. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  79. DatePicker(
  80. "Time",
  81. selection: $state.date,
  82. in: ...now,
  83. displayedComponents: [.hourAndMinute]
  84. ).controlSize(.mini)
  85. .labelsHidden()
  86. Button {
  87. if state.date.addingTimeInterval(5.minutes.timeInterval) < now {
  88. state.date = state.date.addingTimeInterval(10.minutes.timeInterval)
  89. }
  90. }
  91. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  92. }
  93. }
  94. // Optional meal note
  95. HStack {
  96. Text("Note").foregroundColor(.secondary)
  97. TextField("", text: $state.note).multilineTextAlignment(.trailing)
  98. if state.note != "", isFocused {
  99. Button { isFocused = false } label: { Image(systemName: "keyboard.chevron.compact.down") }
  100. .controlSize(.mini)
  101. }
  102. }
  103. .focused($isFocused)
  104. .popover(isPresented: $isPromptPresented) {
  105. presetPopover
  106. }
  107. }
  108. Section {
  109. Button { state.add(override, fetch: editMode) }
  110. label: { Text((state.skipBolus && !override && !editMode) ? "Save" : "Continue") }
  111. .disabled(empty)
  112. .frame(maxWidth: .infinity, alignment: .center)
  113. }.listRowBackground(!empty ? Color(.systemBlue) : Color(.systemGray4))
  114. .tint(.white)
  115. Section {
  116. mealPresets
  117. }
  118. }
  119. .onAppear {
  120. configureView {
  121. state.loadEntries(editMode)
  122. }
  123. }
  124. .navigationTitle("Add Meal")
  125. .navigationBarTitleDisplayMode(.inline)
  126. .navigationBarItems(trailing: Button("Close", action: state.hideModal))
  127. }
  128. private var presetPopover: some View {
  129. Form {
  130. Section {
  131. TextField("Name Of Dish", text: $dish)
  132. Button {
  133. saved = true
  134. if dish != "", saved {
  135. let preset = Presets(context: moc)
  136. preset.dish = dish
  137. preset.fat = state.fat as NSDecimalNumber
  138. preset.protein = state.protein as NSDecimalNumber
  139. preset.carbs = state.carbs as NSDecimalNumber
  140. try? moc.save()
  141. state.addNewPresetToWaitersNotepad(dish)
  142. saved = false
  143. isPromptPresented = false
  144. }
  145. }
  146. label: { Text("Save") }
  147. Button {
  148. dish = ""
  149. saved = false
  150. isPromptPresented = false }
  151. label: { Text("Cancel") }
  152. } header: { Text("Enter Meal Preset Name") }
  153. }
  154. }
  155. private var empty: Bool {
  156. state.carbs <= 0 && state.fat <= 0 && state.protein <= 0
  157. }
  158. private var minusButton: some View {
  159. Button {
  160. if state.carbs != 0,
  161. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  162. {
  163. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  164. } else { state.carbs = 0 }
  165. if state.fat != 0,
  166. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  167. {
  168. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  169. } else { state.fat = 0 }
  170. if state.protein != 0,
  171. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  172. {
  173. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  174. } else { state.protein = 0 }
  175. state.removePresetFromNewMeal()
  176. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  177. }
  178. label: { Image(systemName: "minus.circle") }
  179. .disabled(
  180. state
  181. .selection == nil ||
  182. (
  183. !state.summation
  184. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  185. )
  186. )
  187. .buttonStyle(.borderless)
  188. .tint(.blue)
  189. }
  190. private var plusButton: some View {
  191. Button {
  192. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  193. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  194. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  195. state.addPresetToNewMeal()
  196. }
  197. label: { Image(systemName: "plus.circle") }
  198. .disabled(state.selection == nil)
  199. .buttonStyle(.borderless)
  200. .tint(.blue)
  201. }
  202. private var mealPresets: some View {
  203. Section {
  204. HStack {
  205. if state.selection != nil {
  206. minusButton
  207. }
  208. Picker("Preset", selection: $state.selection) {
  209. Text("Saved Food").tag(nil as Presets?)
  210. ForEach(carbPresets, id: \.self) { (preset: Presets) in
  211. Text(preset.dish ?? "").tag(preset as Presets?)
  212. }
  213. }
  214. .labelsHidden()
  215. .frame(maxWidth: .infinity, alignment: .center)
  216. ._onBindingChange($state.selection) { _ in
  217. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  218. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  219. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  220. state.addToSummation()
  221. }
  222. if state.selection != nil {
  223. plusButton
  224. }
  225. }
  226. HStack {
  227. Button("Delete Preset") {
  228. showAlert.toggle()
  229. }
  230. .disabled(state.selection == nil)
  231. .tint(.orange)
  232. .buttonStyle(.borderless)
  233. .alert(
  234. "Delete preset '\(state.selection?.dish ?? "")'?",
  235. isPresented: $showAlert,
  236. actions: {
  237. Button("No", role: .cancel) {}
  238. Button("Yes", role: .destructive) {
  239. state.deletePreset()
  240. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  241. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  242. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  243. state.addPresetToNewMeal()
  244. }
  245. }
  246. )
  247. Spacer()
  248. Button {
  249. isPromptPresented = true
  250. }
  251. label: { Text("Save as Preset") }
  252. .buttonStyle(.borderless)
  253. .disabled(
  254. empty ||
  255. (
  256. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  257. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  258. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  259. .protein
  260. )
  261. )
  262. }
  263. }
  264. }
  265. @ViewBuilder private func proteinAndFat() -> some View {
  266. HStack {
  267. Text("Fat").foregroundColor(.orange)
  268. Spacer()
  269. DecimalTextField(
  270. "0",
  271. value: $state.fat,
  272. formatter: formatter,
  273. autofocus: false,
  274. cleanInput: true
  275. )
  276. Text("grams").foregroundColor(.secondary)
  277. }
  278. HStack {
  279. Text("Protein").foregroundColor(.red)
  280. Spacer()
  281. DecimalTextField(
  282. "0",
  283. value: $state.protein,
  284. formatter: formatter,
  285. autofocus: false,
  286. cleanInput: true
  287. ).foregroundColor(.loopRed)
  288. Text("grams").foregroundColor(.secondary)
  289. }
  290. }
  291. }
  292. }
  293. public extension Color {
  294. static func randomGreen(randomOpacity: Bool = false) -> Color {
  295. Color(
  296. red: .random(in: 0 ... 1),
  297. green: .random(in: 0.4 ... 0.7),
  298. blue: .random(in: 0.2 ... 1),
  299. opacity: randomOpacity ? .random(in: 0.8 ... 1) : 1
  300. )
  301. }
  302. }