AddCarbsRootView.swift 14 KB

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