AddCarbsRootView.swift 13 KB

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