AddCarbsRootView.swift 14 KB

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