AddCarbsRootView.swift 14 KB

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