AddCarbsRootView.swift 14 KB

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