AddCarbsRootView.swift 14 KB

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