AddCarbsRootView.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. Color(red: 0.011, green: 0.058, blue: 0.109),
  157. Color(red: 0.03921568627, green: 0.1333333333, blue: 0.2156862745)
  158. ]),
  159. startPoint: .bottom,
  160. endPoint: .top
  161. )
  162. :
  163. LinearGradient(gradient: Gradient(colors: [Color.gray.opacity(0.1)]), startPoint: .top, endPoint: .bottom)
  164. }
  165. private var empty: Bool {
  166. state.carbs <= 0 && state.fat <= 0 && state.protein <= 0
  167. }
  168. private var minusButton: some View {
  169. Button {
  170. if state.carbs != 0,
  171. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  172. {
  173. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  174. } else { state.carbs = 0 }
  175. if state.fat != 0,
  176. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  177. {
  178. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  179. } else { state.fat = 0 }
  180. if state.protein != 0,
  181. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  182. {
  183. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  184. } else { state.protein = 0 }
  185. state.removePresetFromNewMeal()
  186. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  187. }
  188. label: { Image(systemName: "minus.circle") }
  189. .disabled(
  190. state
  191. .selection == nil ||
  192. (
  193. !state.summation
  194. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  195. )
  196. )
  197. .buttonStyle(.borderless)
  198. .tint(.blue)
  199. }
  200. private var plusButton: some View {
  201. Button {
  202. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  203. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  204. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  205. state.addPresetToNewMeal()
  206. }
  207. label: { Image(systemName: "plus.circle") }
  208. .disabled(state.selection == nil)
  209. .buttonStyle(.borderless)
  210. .tint(.blue)
  211. }
  212. private var mealPresets: some View {
  213. Section {
  214. HStack {
  215. if state.selection != nil {
  216. minusButton
  217. }
  218. Picker("Preset", selection: $state.selection) {
  219. Text("Saved Food").tag(nil as Presets?)
  220. ForEach(carbPresets, id: \.self) { (preset: Presets) in
  221. Text(preset.dish ?? "").tag(preset as Presets?)
  222. }
  223. }
  224. .labelsHidden()
  225. .frame(maxWidth: .infinity, alignment: .center)
  226. ._onBindingChange($state.selection) { _ in
  227. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  228. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  229. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  230. state.addToSummation()
  231. }
  232. if state.selection != nil {
  233. plusButton
  234. }
  235. }
  236. HStack {
  237. Button("Delete Preset") {
  238. showAlert.toggle()
  239. }
  240. .disabled(state.selection == nil)
  241. .tint(.orange)
  242. .buttonStyle(.borderless)
  243. .alert(
  244. "Delete preset '\(state.selection?.dish ?? "")'?",
  245. isPresented: $showAlert,
  246. actions: {
  247. Button("No", role: .cancel) {}
  248. Button("Yes", role: .destructive) {
  249. state.deletePreset()
  250. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  251. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  252. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  253. state.addPresetToNewMeal()
  254. }
  255. }
  256. )
  257. Spacer()
  258. Button {
  259. isPromptPresented = true
  260. }
  261. label: { Text("Save as Preset") }
  262. .buttonStyle(.borderless)
  263. .disabled(
  264. empty ||
  265. (
  266. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  267. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  268. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  269. .protein
  270. )
  271. )
  272. }
  273. }
  274. }
  275. @ViewBuilder private func proteinAndFat() -> some View {
  276. HStack {
  277. Text("Fat").foregroundColor(.orange)
  278. Spacer()
  279. DecimalTextField(
  280. "0",
  281. value: $state.fat,
  282. formatter: formatter,
  283. autofocus: false,
  284. cleanInput: true
  285. )
  286. Text("grams").foregroundColor(.secondary)
  287. }
  288. HStack {
  289. Text("Protein").foregroundColor(.red)
  290. Spacer()
  291. DecimalTextField(
  292. "0",
  293. value: $state.protein,
  294. formatter: formatter,
  295. autofocus: false,
  296. cleanInput: true
  297. ).foregroundColor(.loopRed)
  298. Text("grams").foregroundColor(.secondary)
  299. }
  300. }
  301. }
  302. }
  303. public extension Color {
  304. static func randomGreen(randomOpacity: Bool = false) -> Color {
  305. Color(
  306. red: .random(in: 0 ... 1),
  307. green: .random(in: 0.4 ... 0.7),
  308. blue: .random(in: 0.2 ... 1),
  309. opacity: randomOpacity ? .random(in: 0.8 ... 1) : 1
  310. )
  311. }
  312. }